Question

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.example.com/xml-to-parse.xml");
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

$element = $xmlDoc->getElementsByTagName('Root');

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

The error I am getting is:

Trying to get property of non-object

Was it helpful?

Solution

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.

OTHER TIPS

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top