php 获取XML字符串中第二级标记的名称

ryevplcw  于 11个月前  发布在  PHP
关注(0)|答案(2)|浏览(83)

我试图从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

sq1bmfud

sq1bmfud1#

您可以简单地遍历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

ymzxtsji

ymzxtsji2#

正如在Using XPath to extract XML in PHP中所演示的,(虽然在所问的问题中不是必需的)xpath是一个非常直接的工具,可以提取未知的标记名,而无需循环检查。
代码:(Demo

$dom = new DOMDocument();
$dom->loadxml($xml);
$xpath = new DOMXPath($dom);
echo $xpath->evaluate('string(/types/type[@name]/@name)');
// ACOGOptic

字符串

相关问题