【问题标题】:How to get the value of a specific nested XML node in PHP?如何在 PHP 中获取特定嵌套 XML 节点的值?
【发布时间】:2017-09-12 06:37:34
【问题描述】:

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

<?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"]')

【问题讨论】:

  • 请出示您的代码。
  • //custom_field[@Name="ZIP"] 不起作用吗?
  • 似乎在这里工作得很好~eval.in/859806。我建议你仔细看看$rm_host."/projects.xml?key=".$rm_sa_key."&amp;limit=100" 正在返回什么

标签: php xml xpath


【解决方案1】:

试了再试,终于成功了。

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

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

xpath 前面没有斜线。

【讨论】:

  • 有多种方法可以测试您的 XPath,在线测试人员如 xpathtester.com/xpath,或者我使用 Eclipse,我可以检查表达式将交互返回什么。 //custom_fields/custom_field[@name="ZIP"]/value 应该像您在此处实现的那样使用 XPath 来完成类似的工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多