我有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
医生.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>
测试.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);
}
?>
好吧,您的查询几乎是正确的。你刚刚忘记了把最后关闭"]
" 字符。
它应该是:
$tags = $xpath->query('//div[@id="tag-id"]');
相反:
$tags = $xpath->query('//div[@id="tag-id"');