Heim  >  Artikel  >  Backend-Entwicklung  >  PHP获取远程网页内容(fopen,curl方式)

PHP获取远程网页内容(fopen,curl方式)

WBOY
WBOYOriginal
2016-07-25 08:54:231164Durchsuche
  1. $handle = fopen ("http://bbs.it-home.org/", "rb");

  2. $contents = "";
  3. while (!feof($handle)) {
  4. $contents .= fread($handle, 8192);
  5. }
  6. fclose($handle);
  7. echo $contents; //输出获取到得内容。
  8. ?>
  9. // 对 PHP 5 及更高版本可以使用下面的代码

  10. $handle = fopen("http://bbs.it-home.org", "rb");
  11. $contents = stream_get_contents($handle);
  12. fclose($handle);
  13. echo $contents;
  14. ?>
复制代码

以上代码容易出现 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)"

在工作中遇到这个问题,后完美解决,故分享给大家。

php获取远程网页内容

2、通过curl来实现

  1. $url = "http://bbs.it-home.org";
  2. $ch = curl_init();
  3. curl_setopt ($ch, CURLOPT_URL, $url);
  4. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  5. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
  6. $dxycontent = curl_exec($ch);
  7. echo $dxycontent;
  8. ?>
复制代码

linux系统中可以使用以下代码下载 exec("wget {$url}");

附,PHP抓取外部资源函数fopen / file_get_contents / curl 的区别。 fopen / file_get_contents 每次请求都会重新做DNS查询,并不对DNS信息进行缓存。 但是CURL会自动对DNS信息进行缓存。对同一域名下的网页或者图片的请求只需要一次DNS查询。 这大大减少了DNS查询的次数。 所以CURL的性能比fopen / file_get_contents 好很多。



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn