Saturday, 4 April 2015

PHP - How to check for element each loop?



I am using the below loop to parse an XML file.



$link = $item->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$image = $item->getElementsByTagName('enclosure')->item(0)->getAttribute('url');


However, Some times the XML item doesn't have an 'enclosure' element and my entire page fails with the below error



PHP Fatal error: Call to a member function getAttribute() on a non-object


How can I check for the element each loop and replace the $image variable with a static string if it doesn't exist?


No comments:

Post a Comment