0

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.

ty812
3,33322 silver badges37 bronze badges
asked Oct 17, 2009 at 19:48
2
  • Sorry i meant as a foreach statement on the fourth line there Commented Oct 17, 2009 at 19:49
  • Can you update (edit) your post to reflect correct code Commented Oct 17, 2009 at 19:53

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

you don't really need the >0 check, but this will do what you want.
THANK YOU SO MUCH!! Been stuck on it since yesterday! Works!
@meder do you khow why sometimes I get non-object error but the object is exists in xml? stackoverflow.com/questions/18096972/…
No, I think you should post this problem as separate question

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.