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

如何在PHP中获取特定嵌套XML节点的值?,php,xml,xpath,Php,Xml,Xpath,我需要使用PHP从下面的XML文件中获取每个名为“ZIP”的“custom_字段”的值。 当我解析它时,我总是得到所有项目的值或者一个空数组? 有人能帮忙吗 <?xml version="1.0" encoding="UTF-8"?> <projects total_count="237" offset="0" limit="100" type="array"> <project> <id>239</id> <na

我需要使用PHP从下面的XML文件中获取每个名为“ZIP”的“custom_字段”的值。 当我解析它时,我总是得到所有项目的值或者一个空数组? 有人能帮忙吗

<?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>
...

试了又试,终于成功了

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

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

xpath前面没有斜杠。

请显示您的代码。与之相似的是
//自定义_字段[@Name=“ZIP”]
不起作用?在这里似乎工作得很好~。我建议您仔细看看
$rm\u host./projects.xml?key=“.rm\u sa\u key.&limit=100”
返回的内容有多种方法可以测试XPath,在线测试人员喜欢,或者我使用Eclipse,我可以检查表达式将以交互方式返回的内容
//custom_fields/custom_field[@name=“ZIP”]/value
应该像您在这里实现的那样使用XPath完成类似的工作。
zip = $project->xpath('//custom_fields[@type="array"]/custom_field[@name="ZIP"]')
$zip = $project->custom_fields->xpath('custom_field[@name="ZIP"]/value')[0];