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.
asked Oct 17, 2009 at 19:48
David Willis
1,0927 gold badges15 silver badges23 bronze badges
-
Sorry i meant as a foreach statement on the fourth line thereDavid Willis– David Willis2009年10月17日 19:49:49 +00:00Commented Oct 17, 2009 at 19:49
-
Can you update (edit) your post to reflect correct codeIvan Nevostruev– Ivan Nevostruev2009年10月17日 19:53:53 +00:00Commented Oct 17, 2009 at 19:53
1 Answer 1
Try to do use length property of DOMNodeList:
$nodes = $feeditem->getElementsByTagName('extra');
if ($nodes->length > 0) {
$extraname = $extratag->item(0)->getAttribute('name');
}
answered Oct 17, 2009 at 19:51
Ivan Nevostruev
28.9k8 gold badges69 silver badges82 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
meder omuraliev
you don't really need the
>0 check, but this will do what you want.David Willis
THANK YOU SO MUCH!! Been stuck on it since yesterday! Works!
Pooya
@meder do you khow why sometimes I get non-object error but the object is exists in xml? stackoverflow.com/questions/18096972/…
Ivan Nevostruev
No, I think you should post this problem as separate question
default