查询数组名称

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

度过了一个非常愚蠢的时刻..

我正在尝试从 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>

如何简单地获取 type name="XX" 的值? 因此,在上述数据片段的情况下,它将获取 ACOGOptic

php simplexml
1个回答
0
投票

您可以简单地迭代

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>1</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', $type->nominal, $type->quantmin, $type->quantmax);
}

输出:

Nominal: 15  Min: -1  Max: -1
© www.soinside.com 2019 - 2024. All rights reserved.