tags:

views:

624

answers:

2

HI Guys, I'm using DOM to parse an xml file. And I am having trouble catching an error that throws when the XML tag is empty and self closed.

eg. <Title />

$xml=("http://www.exampleUrl.com/xmltoparse.xml");
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

$x=$xmlDoc->getElementsByTagName('Root');
for ($i=0; $i<=10; $i++)
{
$id=$x->item($i)->getElementsByTagName('Title')
->item(0)->childNodes->item(0)->nodeValue;

The error I am getting is: "Trying to get property of non-object"

Would appreciate the help.

+1  A: 

An empty tag is not going to have any child nodes, thus the second item(0) in your last line is not going to return a valid object, and so attempting to get its value via nodeValue is going to throw the error you're getting because it doesn't have a proper object to work on.

Amber
Thanks, I thought as much.My main problem is finding a way to check if the the tag has any child Nodes.I've tried "item(0)->hasChildNodes" but have had no luck.Any Ideas?
JordanC
Could you add the code that you were trying with hasChildNodes?
Amber
Nevermind I have resolved it now. I removed the "childNodes->item(0)->" and it works fine. Thanks for your help!
JordanC
+1  A: 

The XML error you're receiving isn't due to the tag being self-closing; that's valid XML. It's likely due to not finding a tag named Title, or there not being 10 of them returned (which is a bad way to write it anyway, better to base the loop off of $x->length, which is a known value).

scotts
Thanks for that suggestion.I have changed it to X->length but the error is still there.My problem is there are 10 different $x items to loop through and only one of them is empty with the self closing tag. I need a way of checking if the tag is empty. Would you be able to help at all?
JordanC
The hasAttributes() function will tell you if it's an empty (self-closing) tag: http://us2.php.net/manual/en/domnode.hasattributes.php
scotts
Correction: my above comment won't tell you if it's an *empty* tag -- it could still contain other tags, it will just tell you if it has attributes. hasChildNodes() will tell you if it has children. http://us2.php.net/manual/en/domnode.haschildnodes.php
scotts