获取XML字符串中二级标签的名称

问题描述 投票:0回答:2

我正在尝试从 XML 文件获取数据并将其转换为 JSON。

$xml = simplexml_load_file('types.xml','SimpleXMLElement',LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

XML 文件包含的数据结构如下:

<types>
    <type name="ACOGOptic">
        <nominal>15</nominal>
        <lifetime>14400</lifetime>
        <restock>1800</restock>
        <min>8</min>
        <quantmin>-1</quantmin>
        <quantmax>-1</quantmax>
        <cost>100</cost>
        <flags count_in_cargo="0" count_in_hoarder="0" count_in_map="1" count_in_player="0" crafted="0" deloot="0"/>
        <category name="weapons"/>
        <usage name="Military"/>
    </type>
</types>

如何简单地获取类型 name="XX" 的值?

在上述情况下,期望的结果将是

ACOGOptic

php xml-parsing attributes simplexml text-extraction
2个回答
2
投票

您可以简单地迭代

type
元素并检查
name
属性的值:

$xml = <<<XML
<types>
    <type name="ACOGOptic">
        <nominal>15</nominal>
        <lifetime>14400</lifetime>
        <restock>1800</restock>
        <min>8</min>
        <quantmin>-1</quantmin>
        <quantmax>-1</quantmax>
        <cost>100</cost>
        <flags count_in_cargo="0" count_in_hoarder="0" count_in_map="1" count_in_player="0" crafted="0" deloot="0"/>
        <category name="weapons"/>
        <usage name="Military"/>
    </type>
    <type name="Other">
        <nominal>20</nominal>
        <quantmin>0</quantmin>
        <quantmax>30</quantmax>
    </type>
</types>
XML;

$sx = simplexml_load_string($xml);
foreach($sx->type as $type)
{
    if($type['name'] == 'ACOGOptic')
        printf('Nominal: %s  Min: %s  Max: %s  Category: %s', $type->nominal, $type->quantmin, $type->quantmax, $type->category['name']);
}

输出:

Nominal: 15  Min: -1  Max: -1  category: weapons

0
投票

使用 XPath 在 PHP 中提取 XML 所示,(尽管所提出的问题中不需要)xpath 是一个非常直接的工具,可以提取未知标签名称,无需循环检查。

代码:(演示

$dom = new DOMDocument();
$dom->loadxml($xml);
$xpath = new DOMXPath($dom);
echo $xpath->evaluate('string(/types/type[@name]/@name)');
// ACOGOptic
© www.soinside.com 2019 - 2024. All rights reserved.