从DOMXPath查询结果获取属性值?

时间:2013-04-06 10:53:25

标签: php xml dom domdocument domxpath

我正在尝试搜索XML文件并返回与给定条件匹配的记录的所有数据。这是我现在的样子,它搜索得很好,但我似乎无法弄清楚如何在同一记录中获得其他属性的值。

以下是将使用的XML文件示例:

<routing>
    <route>
        <url>/homepage</url>
        <file>/pages/home.php</file>
    </route>
</routing>

以下是我在文档中查找特定记录的方法。它完美地找到它们,但是如何从匹配的记录中获取数据呢?

    $qExp = '//route[url="/homepage"]';
    foreach($inst->query($qExp) as $key=>$node) {
        print_r($node);
        // echo $node->file->nodeValue;
        // how would I do this? I can't seem to
        // access specific attributes at all
        // inside of the DOMXPath class
    }

DOMXPath对象将存储在$node中,但如何使用DOMXPath对象获取其他属性值?例如,此查询将返回第一个XML记录,但我如何具体获取file属性的值?我知道有一个nodeValue函数可用,但它会将所有字段的值一起返回,而我无法对哪些部分属于哪些字段进行排序。

提前感谢您提供任何帮助,这确实让我烦恼。

1 个答案:

答案 0 :(得分:-1)

要获得一个简单易用的解决方案,请使用simplexml

$xml = simplexml_load_string($x); // assuming XML in $x
$result = $xml->xpath("//route[url='/homepage']");

// loop
foreach ($result as $r) echo $r->file,"<br />";

// direct access
echo $result[0]->file,"<br />";

查看live-demo @ http://codepad.viper-7.com/ZRrUPl