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_dump
is just saying that you have a DOMNodeList
object. Traverse the list and you'll see it's there:
foreach( $links as $a) {
echo $a->nodeName . ' ' . $a->nodeValue;
}
This would output:
a Bar
Since it's an <a>
tag, and its contents are Bar
.
Not sure what you are expecting out of the var_dump
, but the element is included in that nodelist as you can see:
var_dump($links->item(0));
//object(DOMElement)#3 (0) {}
var_dump($links->item(0)->getAttribute("href"));
//string(3) "foo"