Question

I have the following script

public function NewsRss() {
$rss = new DOMDocument();
libxml_use_internal_errors(true);
$rss->load('http://www.autoexpress.co.uk/feeds/all');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
  $htmlStr = $node->getElementsByTagName('description')->item(0)->nodeValue;
  $html = new DOMDocument();        
  $html->loadHTML($htmlStr);
  $desc = $html->getElementsByTagName('p')->item(0)->nodeValue;
  //var_dump($desc);
  $imgTag = $html->getElementsByTagName('img');
  $img = ($imgTag->length==0)?'noimg.png':$imgTag->item(0)->getAttribute('src');
  $item = array (
    'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
    'desc' => $desc,
    'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
    'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
'image' => $img,
  );
  array_push($feed, $item);
}
$limit = 3;
for($x=0;$x<$limit;$x++) {
  $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
  $link = $feed[$x]['link'];
  $description = $feed[$x]['desc'];
  $date = date('l F d, Y', strtotime($feed[$x]['date']));
  echo '<div class="news-row-index">';
  echo '<div class="details-index"><p><h5><a href="'.$link.'" target="_blank" title="'.$title.'">'.$title.'</a></h5>';
  echo '<small><em>Posted on '.$date.'</em></small></p>';
  echo '<div class="img"><a href="'.$link.'" target="_blank" title="'.$title.'"><img src="'.$feed[$x]['image'].'" height="79" width="89"></a></div>';
  echo '<p>'.$description.'</p></div>';
  echo '</div>';
}
echo '<a style="margin-left:10px;" class="view-all-but" target="_blank" href="http://www.autoexpress.co.uk/feeds/all">View all</a>';

}

The problem is that us showing me a notice like this Notice: Trying to get property of non-object in on line 10 which is $desc = $html->getElementsByTagName('p')->item(0)->nodeValue; but if I hide the errors everything works fine, just that i am trying to clean up my script of errors, and on this case don't know exactly where to start. I know that -> should not be used many times. Please help me on this, it will be much appreciated. I am kind of a noob in OOP and rss.

Was it helpful?

Solution

It looks like there are no p tags found, so the call to getElementsByTagName returns an empty list, and then you try to call item(0) on an empty list, which is why you get the error.

You could split it over 2 lines to check for no elements:

$p = $html->getElementsByTagName("p");
if($p->length > 0) {
    $desc = $p->item(0)->nodeValue;
} else {
    $desc = "";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top