2014-10-26 101 views
0

我有一个测试文件,我试图用SimpleXML的xpath方法分析一个xml字符串。xml xpath不返回节点值

当我尝试直接使用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>[email protected]</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>[email protected]</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("https://stackoverflow.com/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("https://stackoverflow.com/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>"; 
} 
+0

位混淆。结果将返回所有三个查询。你只是无法获取数据吗? – rjdown 2014-10-26 18:55:39

回答

0

作为每手动http://uk1.php.net/manual/en/simplexmlelement.xpath.php

中的XPath方法搜索儿童匹配XPath路径的SimpleXML节点。

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

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

相反,您可以直接回显该值。那么,几乎直接(他们仍然是simplexml对象)...

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

好的。我认为使用'print_r'会打印孩子及其值。我只是计划解析你的建议。谢谢! – 2014-10-26 19:12:19

+0

你应该看到print_r的一些东西......我为你的第一个和第三个例子得到这个:'Array([0] => SimpleXMLElement Object([0] => Sheila)[1] => SimpleXMLElement Object([0] =>布鲁斯))' – rjdown 2014-10-26 19:14:22

+0

有趣的是,我得到了同样的结果,只有我没有价值的地方,你得到的名字。 (这里的额外两个元素是从多个XML我修剪出计算器描述的):'( [0] => SimpleXMLElement对象 ( ) [1] => SimpleXMLElement对象 ( ) [ 2] => SimpleXMLElement对象 ( ) [3] => SimpleXMLElement对象 ( ) )' – 2014-10-26 19:15:29