file() file_get_contents() fopen()

1.file_get_contents

PHP代码

  1. <?php   
  2. $url = http://www.xxx.com/;
  3. $contents = file_get_contents($url);
  4. //如果出现中文乱码使用下面代码
  5. //$getcontent = iconv("gb2312", "utf-8",file_get_contents($url));
  6. //echo $getcontent;
  7. echo $contents;
  8. ?>  

2.curl

PHP代码

  1. <?php   
  2. $url = "http://www.xxx.com/";
  3. $ch = curl_init();
  4. $timeout = 5;
  5. curl_setopt($ch, CURLOPT_URL, $url);
  6. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  7. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  8. //在需要用户检测的网页里需要增加下面两行
  9. //curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  10. //curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD);
  11. $contents = curl_exec($ch);
  12. curl_close($ch);
  13. echo $contents;
  14. ?>

3.fopen->fread->fclose

PHP代码

  1. <?php   
  2. $handle = fopen ("http://www.xxx.com/", "rb");
  3. $contents = "";
  4. do {
  5.    $data = fread($handle, 8192);
  6.    if (strlen($data) == 0) {
  7.    break;
  8.     }
  9.    $contents .= $data;
  10. } while(true);
  11. fclose ($handle);
  12. echo $contents;
  13. ?>

Ps1.使用file_get_contents和fopen必须空间开启allow_url_fopen。方法:编辑php.ini,设置allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。 Ps2.使用curl必须空间开启curl。方法:WIN下修改php.ini,将extension=php_curl.dll前面的分号去掉,而且需要拷贝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux下要安装curl扩展。

 

 

建议打开URL时使用file_get_contents()方法,可优化打开速度

posted on 2014-01-19 16:19  andydaopeng  阅读(288)  评论(0编辑  收藏  举报

导航