PHP file_get_contents causes page to be inaccessible
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
fo开发者_JAVA技巧reach($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;
}
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.
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.
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?
精彩评论