Search code examples
phpparsingrsssimplepie

Include a php library and cant access it from another php page


Im loading the php rss parsing library simplepie onto my site and i include it in the header.php file like so:

<?php
    // Make sure that SimplePie is loaded
require_once('inc/simplepie.inc');
$feed = new SimplePie('rss.com'); <-- This is a example url

// Make sure the content is being served out to the browser properly.
$feed->handle_content_type();

?>

Then i try to access the object from another page called page.php and it gives me this error:

Fatal error: Call to a member function get_items() on a non-object in /home/callofdu/public_html/wp-content/themes/Starkers/page.php on line 13

I get the error from this line of code:

<?php
foreach ($feed->get_items() as $item)
{}
?>

Its weird because if i include both of those chuncks of code together on the same php page it all works fine.

I just am not understanding something, please help.


Solution

  • Several things could be wrong here:

    1. Code order is incorrect.
      Realise that when you require or include a PHP file, the entire code of that file will be executed at that point. In other words: interpret the command require_once as "Insert file contents here", and check whether the order of lines of code are still right.

    2. You are calling page.php in a separate request.
      If you use your browser to manually surf to page.php after the completeion of the previous page, $feed will no longer exist. If you do want it to live on between requests, do the following:

      a. Replace all instances of $feed with $_SESSION['feed']
      b. In the first line of every file that you surf to (so not the require'd files), put session_start();