且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP DOMDocument在NodeList上调用getElementsByTagName

更新时间:2023-11-18 15:32:58

您没有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 called container.

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 of load.