现在的位置: 首页 > 综合 > 正文

file_get_contents返回为空或函数不可用的解决方案

2013年01月18日 ⁄ 综合 ⁄ 共 1752字 ⁄ 字号 评论关闭

如果你使用file_get_contents获取远程文件内容返回为空或提示该函数不可用,也许本文能帮到你!

使用file_get_contents和fopen必须空间开启allow_url_fopen。方法:编辑php.ini,设置allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。如果你使用的是虚拟主机可以考虑用curl函数来代替。

curl函数的使用示例:

  1. $ch = curl_init();
  2. $timeout = 5;
  3. curl_setopt ($ch, CURLOPT_URL, ‘http://www.hujuntao.com’);
  4. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  5. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  6. $file_contents = curl_exec($ch);
  7. curl_close($ch);

利用function_exists函数来判断php是否支持file_get_contents,否则用curl函数来代替。

PS
1、如果你的主机服务商把curl也关闭了,那你还是换个主机商吧!
2、allow_url_fopen设为off,并不代表你的主机不支持file_get_content函数。只是不能打开远程文件而已。function_exists(‘file_get_contents’)返回的是true。所以网上流传的《file_get_contents函数不可用的解决方法》还是不能解决问题。
错误代码:

  1. if (function_exists(‘file_get_contents’)) {
  2. $file_contents = @file_get_contents($url);
  3. }else{
  4. $ch = curl_init();
  5. $timeout = 30;
  6. curl_setopt($ch, CURLOPT_URL, $url);
  7. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  8. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  9. $file_contents = curl_exec($ch);
  10. curl_close($ch);
  11. }

应改为:

  1. if (function_exists(‘file_get_contents’)) {//判断是否支持file_get_contents
  2. $file_contents = @file_get_contents($url);
  3. }
  4. if ($file_contents == ”) {//判断$file_contents是否为空
  5. $ch = curl_init();
  6. $timeout = 30;
  7. curl_setopt($ch, CURLOPT_URL, $url);
  8. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  9. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  10. $file_contents = curl_exec($ch);
  11. curl_close($ch);
  12. }

最终代码:

  1. function file_get_content($url) {
  2. if (function_exists(‘file_get_contents’)) {
  3. $file_contents = @file_get_contents($url);
  4. }
  5. if ($file_contents == ”) {
  6. $ch = curl_init();
  7. $timeout = 30;
  8. curl_setopt($ch, CURLOPT_URL, $url);
  9. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  10. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  11. $file_contents = curl_exec($ch);
  12. curl_close($ch);
  13. }
  14. return $file_contents;
  15. }

用法:

  1. echo file_get_content(‘http://www.hujuntao.com’);

抱歉!评论已关闭.