为什么XPath无法找到标签?

时间:2017-07-04 19:00:59

标签: php xml xpath domdocument

我有xml文件和PHP脚本来处理这个XML。为什么脚本无法找到标签?为什么xpath失败并出现警告:

PHP Warning:  DOMXPath::query(): Invalid predicate in test.php on line 7
PHP Warning:  DOMXPath::query(): Invalid expression in test.php on line 7
PHP Warning:  Invalid argument supplied for foreach() in test.php on line 9

doc.xml

<?xml version="1.0" encoding="UTF-8"?>
<rootTag>
    <div id="tag-id"></div>
    <div id="tag-id"></div>
    <div id="tag-id"></div>
    <div id="tag-id"></div>
    <div id="tag-id"></div>
</rootTag>

test.php的

<?php

$doc = new DOMDocument();
$doc->load('./doc.xml');

$xpath = new DOMXPath($doc);
$tags = $xpath->query('//div[@id="tag-id"');

foreach ($tags as $node) {
    print($node->nodeName);
}

?>

1 个答案:

答案 0 :(得分:1)

嗯,你的查询几乎是正确的。你刚忘记把最后一个关闭“]”char。

它应该是:

$tags = $xpath->query('//div[@id="tag-id"]');

代替:

$tags = $xpath->query('//div[@id="tag-id"');