I’m trying to use the DOMDocument function getElementsByTagName(), but it keeps returning an empty object. I’m using the following code:
// Create some HTML
$output = '
<html>
<body>
<a href="foo">Bar</a>
</body>
</html>';
// Load the HTML
$dom = new DOMDocument;
$dom->loadHTML($output);
// Find all links (a tags)
$links = $dom->getElementsByTagName('a');
var_dump($links); // object(DOMNodeList)#31 (0) { } - empty object
What am I missing? Looking at the documentation, it looks like I’m using the function correctly.
That
var_dumpis just saying that you have aDOMNodeListobject. Traverse the list and you’ll see it’s there:This would output:
Since it’s an
<a>tag, and its contents areBar.