如何在PHP中获取特定嵌套XML节点的值?

时间:2017-09-12 06:37:35

标签: php xml xpath

我需要获得每个" custom_field"的价值。命名" ZIP"使用PHP从以下XML文件中删除。 当我解析它时,我总是得到所有项目的值或空数组? 有人可以帮忙吗?

<?xml version="1.0" encoding="UTF-8"?>
<projects total_count="237" offset="0" limit="100" type="array">
<project>
    <id>239</id>
    <name>ABC</name>
    <identifier></identifier>
    <description></description>
    <status>1</status>
    <is_public>false</is_public>
    <custom_fields type="array">
        <custom_field id="18" name="Name affix">
            <value></value>
        </custom_field>
        <custom_field id="20" name="ZIP">
            <value>X1111</value>
        </custom_field>
    </custom_fields>
    <created_on>2017-06-05T16:33:13Z</created_on>
    <updated_on>2017-06-19T13:46:08Z</updated_on>
</project>
<project>
    <id>240</id>
    <name>DEF</name>
    <identifier></identifier>
    <description></description>
    <status>1</status>
    <is_public>false</is_public>
    <custom_fields type="array">
        <custom_field id="18" name="Name affix">
            <value></value>
        </custom_field>
        <custom_field id="20" name="ZIP">
            <value>Y2222</value>
        </custom_field>
    </custom_fields>
    <created_on>2017-06-05T16:33:14Z</created_on>
    <updated_on>2017-06-05T16:33:14Z</updated_on>
</project>
...

我尝试了以下操作并获得了空数组:

$projects = simplexml_load_file($rm_host."/projects.xml?key=".$rm_sa_key."&limit=100");

foreach($projects->project as $project){

    $zip = $project->xpath('//custom_field[@name="ZIP"]');

    print_r($zip);
    echo "<br/>";
}

当我尝试用以下内容替换字符串时,它返回所有项目的值,而不是特定项目的值:

zip = $project->xpath('//custom_fields[@type="array"]/custom_field[@name="ZIP"]')

1 个答案:

答案 0 :(得分:0)

最后在尝试和尝试后工作。

获取特定值的正确字符串是:

$zip = $project->custom_fields->xpath('custom_field[@name="ZIP"]/value')[0];

在xpath前没有斜杠。