Hi all
Here's a chunk of test XML data I'm using:
<?xml version="1.0" encoding="iso-8859-1" ?>
<calendar>
<gig>
<date>Friday 5 August</date>
<band>Depeche Mode</band>
<time>8.30pm - 11:00pm</time>
<website>http://depechemode.com</website>
</gig>
<gig>
<date>Saturday 6 August</date>
<band>Erasure</band>
<time>8.30pm - 10:30pm</time>
<website>http://erasure.com</website>
</gig>
<gig>
<date>Sunday 7 August</date>
<band>The Unknowns</band>
<time>8.30pm - 10:30pm</time>
</gig>
</calendar>
As you can see, in the last chunk of data, the <website> element is (deliberately) missing. The reason is, I want to be able to leave out elements and have my PHP coding be able to simply ignore elements that aren't there, rather than having to use an empty <website></website> (as I like making my life more complicated than it already is...) 😉
Here's the PHP code that's looping through and outputting the data:
$xmlDoc = new DOMDocument();
$xmlDoc->load('example.xml');
$xmlGigs = $xmlDoc->getElementsByTagName("gig");
$totalGigs = $xmlGigs->length;
for ($i=0; $i<$totalGigs; $i++)
{
echo ($xmlGigs->item($i)->getElementsByTagName("date")->item(0)->nodeValue) . "<br/>";
echo ($xmlGigs->item($i)->getElementsByTagName("band")->item(0)->nodeValue) . "<br/>";
echo ($xmlGigs->item($i)->getElementsByTagName("time")->item(0)->nodeValue) . "<br/>";
echo ($xmlGigs->item($i)->getElementsByTagName("website")->item(0)->nodeValue) . "<br/>";
echo ("<hr/>");
}
And, at the last hurdle, it throws up an error saying:
Notice: Trying to get property of non-object....
Can anyone advise how I can do some simple clean Error Handling to detect that an XML Element doesn't exist and simply skip past it? I've been racking my brain for hours now but none of the approaches tried have worked.
Cheers 🙂