【问题标题】:xml xpath does not return node valuexml xpath 不返回节点值
【发布时间】:2014-10-26 18:32:01
【问题描述】:

我有一个测试文件,我正在尝试使用 SimpleXML 的 xpath 方法解析 xml 字符串。

当我尝试使用 xpath 直接访问节点值时,我得到空输出,但是当我使用 xpath 获取元素然后循环遍历它们时,它工作正常。

当我查看文档时,似乎我的语法应该有效。我有什么遗漏吗?

<?php

$xmlstring = '<?xml version="1.0" encoding="iso-8859-1"?>
<users>
  <user>
    <firstname>Sheila</firstname>
    <surname>Green</surname>
    <address>2 Good St</address>
    <city>Campbelltown</city>
    <country>Australia</country>
    <contact>
      <phone type="mobile">1234 1234</phone>
      <url>http://example.com</url>
      <email>pamela@example.com</email>
    </contact>
  </user>
  <user>
    <firstname>Bruce</firstname>
    <surname>Smith</surname>
    <address>1 Yakka St</address>
    <city>Meekatharra</city>
    <country>Australia</country>
    <contact>
      <phone type="landline">4444 4444</phone>
      <url>http://yakka.example.com</url>
      <email>bruce@yakka.example.com</email>
    </contact>
  </user>
</users>';


// Start parsing
if(!$xml = simplexml_load_string($xmlstring)){
    echo "Error loading string ";
} else {
    echo "<pre>";

    // Print all firstname values directly from xpath
    // This outputs the elements, but the values are blank
    print_r($xml->xpath("/users/user/firstname"));

    // Set a variable with all of the user elements and then loop through and print firstname values
    // This DOES output the values
    $users = $xml->xpath("/users/user");
    foreach($users as $user){
        echo $user->firstname;
    }

    // Find all firstname values by tag
    // This does not output the values 
    print_r($xml->xpath("//firstname"));
    echo "</pre>";
}

【问题讨论】:

  • 有点困惑。将返回所有三个查询的结果。您只是在获取数据时遇到问题吗?

标签: php xml xpath xml-parsing


【解决方案1】:

按照手册http://uk1.php.net/manual/en/simplexmlelement.xpath.php

xpath 方法在 SimpleXML 节点中搜索与 XPath 路径匹配的 children

在您的第一个和第三个示例中,您将返回包含节点值数组的对象,而不是节点本身。所以你将无法做到例如

$results = $xml->xpath("//firstname");
foreach ($results as $result) {
    echo $result->firstname;
}

相反,您可以直接回显该值。嗯,几乎直接(毕竟它们仍然是 simplexml 对象)...

$results = $xml->xpath("//firstname");
foreach ($results as $result) {
    echo $result->__toString();
}

【讨论】:

  • 嗯,好的。我认为使用print_r 会打印出孩子们和他们的价值观。我将计划按照您的建议进行解析。谢谢!
  • 你应该看到 print_r 的东西...我为你的第一个和第三个例子得到这个:Array( [0] =&gt; SimpleXMLElement Object ( [0] =&gt; Sheila ) [1] =&gt; SimpleXMLElement Object ( [0] =&gt; Bruce ))
  • 有趣,我得到了同样的结果,只是我没有你得到名字的值。 (这里额外的两个元素来自我从stackoverflow描述中删除的更多xml):( [0] =&gt; SimpleXMLElement Object ( ) [1] =&gt; SimpleXMLElement Object ( ) [2] =&gt; SimpleXMLElement Object ( ) [3] =&gt; SimpleXMLElement Object ( ) )
  • 是的,当我使用 __toString() 时,我得到了所有名字的值
猜你喜欢
  • 1970-01-01
  • 2016-02-23
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多