PHP DOMDocument在NodeList上调用getElementsByTagName [英] PHP DOMDocument calling getElementsByTagName on a NodeList
问题描述
我正在尝试使用DOMDocument在PHP中遍历DOM树。最初对getElementById / getElementsByTagName的调用是成功的,但是我不确定如何继续生成的NodeList。
这是我尝试遍历的HTML示例文件
<!DOCTYPE html>。
< html>
< div id = container>
< p>你好< / p>
< / div>
< / html>
在Java语言中,我可以像这样链接DOM遍历方法:
document.getElementById('container')。getElementsByTagName('p')[0] .innerText
//返回 Hello
但是在PHP中尝试类似的方法...
<?php
$ document =新的DOMDocument();
$ document-> load('test.html');
echo $ document-> getElementById(’content’)-> getElementsByTagName(’p’)-> item(0)-> nodeValue。 PHP_EOL;
?>
...只是返回此错误:
致命错误:在第6行
我做错了还是根本不支持?
解决方案您没有ID为
content
的元素,它被称为container
。
此外,您不能在任何旧的XML文档上调用
getElementById
。它需要具有将属性定义为ID类型的DTD(摘自该手册)。告诉DOMDocument该文档是HTML(对于浏览器中的Javascript来说是隐式完成的)足以使用该功能。
在这里,您应该调用
DOMDocument :: loadHTMLFile
代替load
。I'm trying to traverse a DOM tree in PHP using DOMDocument. Initial calls to getElementById / getElementsByTagName are successful, but I'm not sure how to proceed with the resulting NodeList.
Here's an example HTML file that I'm trying to traverse.
<!DOCTYPE html> <html> <div id="container"> <p> Hello </p> </div> </html>
In Javascript I'd be able to chain DOM traversal methods like so:
document.getElementById('container').getElementsByTagName('p')[0].innerText // returns "Hello"
However in PHP trying similar ...
<?php $document = new DOMDocument(); $document->load('test.html'); echo $document->getElementById('content')->getElementsByTagName('p')->item(0)->nodeValue . PHP_EOL; ?>
... simply returns this error:
Fatal error: Call to a member function getElementsByTagName() on a non-object in /Users/liam/foobar on line 6
Am I doing something wrong or is this simply not supported?
解决方案You don't have an element with the id
content
-- it's calledcontainer
.Also, you can't call
getElementById
on any old XML document. it needs to have "a DTD which defines an attribute to be of type ID" (from the manual). Telling DOMDocument that the document is HTML (as is done implicitly in the case of Javascript in a browser) is enough to be able to use the function.Here, you should call
DOMDocument::loadHTMLFile
instead ofload
.这篇关于PHP DOMDocument在NodeList上调用getElementsByTagName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!