Maison  >  Article  >  développement back-end  >  PHP 获取远程网页内容的代码

PHP 获取远程网页内容的代码

WBOY
WBOYoriginal
2016-07-25 08:56:451265parcourir
本文介绍下,php实现的获取远程网页内容的几个方法,包括fopen、curl方式,有需要的朋友参考下吧。

分享几段获取远程网页内容的php代码。 1、fopen方式

<?php 
$handle = fopen ("http://bbs.it-home.org/", "rb"); 
$contents = ""; 
while (!feof($handle)) { 
$contents .= fread($handle, 8192); 
} 
fclose($handle); 
echo $contents; //输出获取到得内容。 

//以下适用于php5以上版本 
$handle = fopen("http://bbs.it-home.org", "rb"); 
$contents = stream_get_contents($handle); 
fclose($handle); 
echo $contents; 
?>

如果出现:failed to open stream: HTTP request failed!错误。

解决方法: 在php.ini中,有这样两个选项:allow_url_fopen =on(表示可以通过url打开远程文件),user_agent="PHP"(表示通过哪种脚本访问网络,默认前面有个 " ; " 去掉即可。)重启服务器。 如下图:

完美解决: 设置php.ini里面的user_agent,php默认的user_agent是PHP,我们把它改成Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)来模拟浏览器即可。 user_agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"

2、curl方式

<?php 
$url = "http://bbs.it-home.org"; 
$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_URL, $url); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10); 
$dxycontent = curl_exec($ch); 
echo $dxycontent; 
?> 

备注:linux下可以使用下面的代码下载 exec("wget {$url}");

PHP抓取外部资源函数fopen、file_get_contents、curl 的区别: 1,fopen / file_get_contents 每次请求都会重新做DNS查询,并不对DNS信息进行缓存。 2,CURL会自动对DNS信息进行缓存。对同一域名下的网页或者图片的请求只需要一次DNS查询。 这大大减少了DNS查询的次数。 因此,CURL的性能比fopen、file_get_contents要好,建议使用。



Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn