views:

92

answers:

1

Hello, 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.

+2  A: 

Try to do use length property of DOMNodeList:

$nodes = $feeditem->getElementsByTagName('extra');
if ($nodes->length > 0) {
    $extraname = $extratag->item(0)->getAttribute('name');
}
Ivan Nevostruev
you don't really need the `>0` check, but this will do what you want.
meder
THANK YOU SO MUCH!!Been stuck on it since yesterday!Works!
David Willis