file_get_contents php|file_get_contents url 含有特殊字符获取失败问题处理

时间:2020-11-23  来源:php函数  阅读:

file_get_contents 在文件名包含特殊符号的时候回遇到处理失败的情况,解决办法是使用urlencode函数处理下文件名。

$name="包含特殊符的文件名";
$name=urlencode($name);

$url = "http://phpff.com/{$name}.jpg";
$con = file_get_contents($url);
?>

知识扩充

file_get_contents()模拟referer,cookie, 使用proxy等等

参考代码

ini_set("default_socket_timeout",120);
ini_set("user_agent","MSIE 6.0;");
$context=array("http" => array ("header"=> "Referer: http://www.baidu.com/", ),);
$xcontext = stream_context_create($context);
echo $str=file_get_contents("http://www.111cn.net/",FALSE,$xcontext);

下面是file_get_contents和curl两个函数同样功能的不同写法

file_get_contents函数的使用示例:

< ?php

$file_contents = file_get_contents(‘http://www.zoneself.org/’);

echo $file_contents;

?>
换成curl函数的使用示例:

< ?php

$ch = curl_init();

$timeout = 5;

curl_setopt ($ch, CURLOPT_URL, ‘http://www.ccvita.com’);

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$file_contents = curl_exec($ch);

curl_close($ch);

echo $file_contents;

?>
利用function_exists函数来判断php是否支持一个函数可以轻松写出下面函数:

< ?php

function vita_get_url_content($url) {

if(function_exists(‘file_get_contents’)) {

$file_contents = file_get_contents($url);

} else {

$ch = curl_init();

$timeout = 5;

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;

}

?>

 
          其实上面的这个函数还有待商榷,如果你的主机服务商把file_get_contents和curl都关闭了,上面的函数就会出现错误。那最后的办法就得换空间或者在支持的空间上写接口,在不支持的空间上进行调用了。

file_get_contents php|file_get_contents url 含有特殊字符获取失败问题处理

http://m.bbyears.com/jiaocheng/112168.html

推荐访问:file_get_contents() file_get_contents获取图片下载
相关阅读 猜你喜欢
本类排行 本类最新