David Willis
David Willis

Reputation: 1092

DOMDocument parsing (php)

I am parsing an xml file from an API which I have converted into a DOMDocument in php. This is mostly fine but one problem I have is when I do this:

$feeditem->getElementsByTagName('extra');

as part of a forall statment and the element extra doesn't exist in one of the feeditems I am iterating through in the forall condition then I get an error.

I tried this:

if (!empty($feeditem->getElementsByTagName('extra'))){
$extratag = $feeditem->getElementsByTagName('extra');
    $extraname = $extratag->item(0)->getAttribute('name');
echo $extraname
    }

But I get the error

getAttribute() on a non-object

Note: When the 'extra' element is contained in every feeditem then the code runs perfect. it's just when one of the feed items doesn't contain an 'extra' element I get the error.

Upvotes: 0

Views: 431

Answers (1)

Ivan Nevostruev
Ivan Nevostruev

Reputation: 28713

Try to do use length property of DOMNodeList:

$nodes = $feeditem->getElementsByTagName('extra');
if ($nodes->length > 0) {
    $extraname = $extratag->item(0)->getAttribute('name');
}

Upvotes: 2

Related Questions