xml xpath不返回节点值

时间:2014-10-26 18:32:01

标签: php xml xpath xml-parsing

我有一个测试文件,我正在尝试使用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>";
}

1 个答案:

答案 0 :(得分:0)

根据手册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();
}