0

我正在尝试搜索 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可用的函数,但它会将所有字段的值一起返回,我无法对哪些部分属于哪些字段进行排序。

在此先感谢您的帮助,这确实困扰着我。

4

1 回答 1

-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 />";

见现场演示@http ://codepad.viper-7.com/ZRrUPl

于 2013-04-06T22:50:42.623 回答