October 22, 2024
Chicago 12, Melborne City, USA
PHP

Fix for “Attempt to read property “nodeValue” on null”


I’m using the following to get content from a list of feeds (in my example below only 2):

$urlarray = array(
array( 'name' => 'feed1', 'url' => 'https://example.com/feed1/rss'),
array( 'name' => 'feed2', 'url' => 'https://example.com/feed2/rss'),
);

Then to extract the entry details (title, description) with this:

foreach ( $urlarray as $url ) {
  $rss->load( $url['url'] );
  foreach ( $rss->getElementsByTagName( 'item' ) as $node ) {
  $item = array(
    'site'  => $url['name'],
    'title' => $node->getElementsByTagName( 'title' )->item( 0 )->nodeValue,
    'desc'  => $node->getElementsByTagName( 'description' )->item( 0 )->nodeValue,
    'link'  => $node->getElementsByTagName( 'link' )->item( 0 )->nodeValue,
    'date'  => $node->getElementsByTagName( 'pubDate' )->item( 0 )->nodeValue,   
    'category'  => $node->getElementsByTagName( 'category' )->item( 0 )->nodeValue, //this is the issue
  );
  array_push( $feed, $item );
  }
}

But I get the warning

Attempt to read property "nodeValue" on null

about the category line, probably because some feed entries there is no category.

It’s just a warning, but I suppose it is better to fix it. Is there something I do to get rid of this, like check if the node exists first?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video