Dimitrios Stefos Dimitrios Stefos - 7 months ago 46
PHP Question

DOMDocument returns 500 when using getAttribute()

I have an html iframe code and I want to get the href value of the first a tag. I have this php code

$doc_url = new DOMDocument();

$iframe_links = $doc_url->getElementsByTagName('a');
$iframe_link = $iframe_links[0]->getAttribute('href');

echo $iframe_link;

When I run it locally on xampp everything is ok. But when I run it on a nginx webserver (digitalocean), I get an HTTP 500.

PHP message: PHP Fatal error: Cannot use object of type DOMNodeList as array

FYI If I remove
$iframe_link = $iframe_links[0]->getAttribute('href');
, it doesn't return an error.


If you receive that error it's because on your server you have an older version of PHP.

You can use DOMNodeList as array only from version 5.6 . Check here

If you want to work on your server that have an older version you need to get the item from element 0 using the method item() like this: