PHP DOMDocument 在 NodeList 上调用 getElementsByTagName
我正在尝试使用 DOMDocument 在 PHP 中遍历 DOM 树。对 getElementById / getElementsByTagName 的初始调用成功,但我不确定如何继续处理生成的 NodeList。
下面是我尝试遍历的 HTML 文件示例。
<!DOCTYPE html>
<html>
<div id="container">
<p> Hello </p>
</div>
</html>
在 Javascript 中,我可以像这样链接 DOM 遍历方法:
document.getElementById('container').getElementsByTagName('p')[0].innerText
// returns "Hello"
但是在 PHP 中尝试类似的......
<?php
$document = new DOMDocument();
$document->load('test.html');
echo $document->getElementById('content')->getElementsByTagName('p')->item(0)->nodeValue . PHP_EOL;
?>
只是返回此错误:
Fatal error: Call to a member function getElementsByTagName() on a non-object in /Users/liam/foobar on line 6
我做错了什么还是这根本不支持?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有 id 为
content
的元素 - 它称为container
。此外,您无法对任何旧 XML 文档调用
getElementById
。它需要有“一个将属性定义为 ID 类型的 DTD”(来自 手册)。告诉 DOMDocument 该文档是 HTML(就像在浏览器中的 Javascript 中隐式完成的那样)就足以使用该函数。在这里,您应该调用
DOMDocument::loadHTMLFile
而不是加载
。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
.在我看来,
$document->getElementById('content')
是空的,您需要将其更改为$document->getElementById('container')
>。It would seem to me that
$document->getElementById('content')
is empty, you need to change it to$document->getElementById('container')
.尝试xpath: http://php.net/manual/en/class.domxpath.php< /a>
Try xpath: http://php.net/manual/en/class.domxpath.php