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

yipeiwu_com5年前PHP代码库
如果你使用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函数的使用示例:
复制代码 代码如下:

$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, ‘//www.jb51.net');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
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函数不可用的解决方法》还是不能解决问题。
错误代码:
复制代码 代码如下:

if (function_exists(‘file_get_contents')) {
$file_contents = @file_get_contents($url);
}else{
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}

应改为:
复制代码 代码如下:

if (function_exists(‘file_get_contents')) {//判断是否支持file_get_contents
$file_contents = @file_get_contents($url);
}
if ($file_contents == ”) {//判断$file_contents是否为空
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}

最终代码:
复制代码 代码如下:

function file_get_content($url) {
if (function_exists(‘file_get_contents')) {
$file_contents = @file_get_contents($url);
}
if ($file_contents == ”) {
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}
return $file_contents;
}

用法:
echo file_get_content(‘//www.jb51.net');

相关文章

PHP 配置文件中open_basedir选项作用

如下是php.ini中的原文说明以及默认配置: ; open_basedir, if set, limits all file operations to the defined dir...

PHP中你应该知道的require()文件包含的正确用法

PHP中你应该知道的require()文件包含的正确用法

以前看一些PHP框架源码的时候,很奇怪在文件包含的时候,会用dirname(__FILE__)来拼凑文件路径,不知道这样做有什么好处,后来终于发现了其中的缘由。 我们来看一个简单的例子:...

PHP实现读取一个1G的文件大小

需求如下: 现有一个1G左右的日志文件,大约有500多万行, 用php返回最后几行的内容。 1. 直接采用file函数来操作 or file_get_content() 肯定报内存溢出注...

PHP封装XML和JSON格式数据接口操作示例

PHP封装XML和JSON格式数据接口操作示例

本文实例讲述了PHP封装XML和JSON格式数据接口操作。分享给大家供大家参考,具体如下: 使用PHP开发app后端的接口时,我们需要返回数据,最常用的就是XML和JSON格式的数据,那...

如何在php中正确的使用json

从5.2版本开始,PHP原生提供json_encode()和json_decode()函数,前者用于编码,后者用于解码。 1、json_encode()该函数主要用来将数组和对象,转换为...