Search code examples
phpxmlparsinggetelementsbytagname

php: xml parse error - non object


I've checked many questions, and I'm not found answer to solve it. I have a lot of xml/rss address that I need to parse in mysql db. It worked good on most xml address. But sometime, some address create error like this.

Fatal error: Call to a member function item() on a non-object in ... on line 61

Line is this:

$item_title=$x->item($n)->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;

full code:

$url = array(
        "http://www.example.com/rss",
          ....      /*This url is from database*/

        "http://www.example.com/rss",

);
$q = 0;

for($j=0;$j<count($url);++$j){

     $xmlDoc = new DOMDocument();
     $xmlDoc->load($url[$j]);        

     //get elements from "<channel>"
     $channel=$xmlDoc->getElementsByTagName('channel')->item(0);
     $channel_title = $channel->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;
     $channel_link = $channel->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;
     $channel_desc = $channel->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;


     $x=$xmlDoc->getElementsByTagName('item');

     for ( $n = 0 ; $n < $x->length ; ++$n ){ 
     /* this line have a problem */
       $item_title=$x->item($n)->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue; 
       $item_link=$x->item($n)->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;
       $item_desc=$x->item($n)->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;

        $query[$q]['xml'] = $url[$j];
        $query[$q]['post_title'] = $item_title;
        $query[$q]['field'] = "xml";
        $query[$q]['id'] = $item_link;
        $query[$q]['description'] = $item_desc;   
            ++$q;
     }  

}


     foreach( $query as $section => $item )
        foreach( $item as $key => $value )
            echo "$section:\t$key\t: $value<br>";   

How can I resolve it?


Solution

  • You cannot expect all of <title>, <link>, and <description> to be in every <item>. Per the RSS Spec:

    All elements of an item are optional, however at least one of title or description must be present.