How would I check if an XML element exists?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lefteh
Forum Newbie
Posts: 1
Joined: Wed Jan 28, 2009 8:57 pm

How would I check if an XML element exists?

Post by lefteh »

My script:

Code: Select all

$feed = "http://www.mysite.com/feed.xml";
 
$doc = new DOMDocument();
$doc->load($feed);
 
$entries = $doc->getElementsByTagName("entry");
 
$datesUsed = array();
 
foreach ($entries as $entry) {
        $status = $entry->getElementsByTagName("eventStatus");
        $eventStatus = $status->item(0)->getAttributeNode("value")->value;
 
        if ($eventStatus == $confirmed) {
                $titles = $entry->getElementsByTagName("title");
                $title = $titles->item(0)->nodeValue;
 
                $times = $entry->getElementsByTagName("when");
 
                $startTime = $times->item(0)->getAttributeNode("startTime")->value;
                $date = date(" F j, Y", strtotime($startTime));
                $time = date("g:i A", strtotime($startTime));
 
                if (!in_array($date, $datesUsed)) {
                        $currentnum = count($datesUsed);
                        if ($currentnum > 0) echo "<br />";
                        echo "<strong>$date</strong><br />";
                        $datesUsed[$currentnum+1] = $date;
                        $arrayyes = 1;
                }
 
                echo $title . " - $time<br />";
        }
}
The script pulls out the “when” element and its attributes. The problem is that not every entry has a when element. How can I skip these records? I am aware of a hasAttribute function, but I can’t seem to find any equivalent for elements. I’ve played around with several techniques, and nothing has worked.

If these entries are not skipped, the following error occurs:
Fatal error: Call to a member function getAttributeNode() on a non-object

Thanks in advance.
User avatar
novice4eva
Forum Contributor
Posts: 327
Joined: Thu Mar 29, 2007 3:48 am
Location: Nepal

Re: How would I check if an XML element exists?

Post by novice4eva »

what about a simple is_object check like :

Code: Select all

 
$times = $entry->getElementsByTagName("when");//check with gettype to see if $times if of type object , if it is then do this
if(is_object($times)){ //then only continue with things}
 
Post Reply