views:

292

answers:

3

Hi, I'm trying to use file_get_contents in php to display an RSS feed. However, when I try to load the page, it fails (as if waiting for something to complete). If I remove the code and save the file again, the page still refuses to work for 5 minutes or so, after which, it goes back to normal. Can anyone help shed any light on what is going on? I use the same code on another site and it works perfectly. Any advice appreciated. Thanks.

   //Displays an xml feed on the page
function display_xml_feed($feed_url, $num_records, $before, $after) {  
      // Get data from feed file
  if(!$response = file_get_contents($feed_url)) {
  return '';
  }

  $xml = simplexml_load_string($response); 
  $count = 0;
  // Browse structure
  foreach($xml->channel->item as $one_item)
  {
    if($count < $num_records)      {
    $html .= $before.'<a href="'.htmlentities($one_item->link).'">'.
    $one_item->title.'</a>'.$after;
    $count++;
    } else {
        break;
    }
  }

   return $html;

}
A: 

Did you try to get a local file? What if you try to get a local feed via http://localhost/myfeed.xml?

maybe file_get_contents takes to much time, this is why I recommend you to try this.

Aif
The feed is on a subdomain of the page i'm trying to put it on, could this be the cause?
Dan
A: 

Is allow_url_fopen (php.ini) set to true? Also you could try to set a timeout for the request.

If you are opening a local file,how big is said file?

Stefan Ernst
all_url_fopen is OnThe file isn't particularly big, it's just (5 or so blog entries) text.
Dan
+2  A: 

The other answers here beat me to my initial thoughts (checking php.ini, a very slow connection to the feed server) but I did notice something else. I'm a Javascript coder with some PHP knowledge (mostly because the syntax is very similar). The following line would cause problems in Javascript because it's not valid syntax:

if(!$response = file_get_contents($feed_url)) {

It might be fine in PHP (if it is add a comment and I'll delete the answer), but in JS you would need to wrap braces around the statement after the !:

if (!($response = file_get_contents($feed_url))) {

Like I said, it might not have even been worth mentioning, but you never know.

Andy E
Not an issue. See the note just above the comments: http://php.net/manual/en/language.operators.precedence.php
Yacoby
Thanks Yacoby, I learn something new about PHP every day!
Andy E
It might not be an issue, but it sure is ugly and difficult to understand (hence Andy's question). I think readability is pretty important, and you shouldn't use something just because it works.
iddqd