09/03 2

PHP读取远程文件的三种方法 不指定

jason , 14:05 , 我的收藏 » PHP , 评论(0) , 引用(0) , 阅读(1111) , Via 本站原创 | |

1.file_get_contents

PHP代码
        
  1. <?php  
  2.     
  3. $url = http://www.xxx.com/;  
  4.     
  5. $contents = file_get_contents($url);  
  6.     
  7. //如果出现中文乱码使用下面代码  
  8.     
  9. //$getcontent = iconv(”gb2312″, “utf-8″,file_get_contents($url));  
  10.     
  11. //echo $getcontent;  
  12.     
  13. echo $contents;  
  14.     
  15. ?>  

2.curl

PHP代码
        
  1. <?php  
  2.     
  3. $url = “http://www.xxx.com/”;  
  4.     
  5. $ch = curl_init();  
  6.     
  7. $timeout = 5;  
  8.     
  9. curl_setopt($ch, CURLOPT_URL, $url);  
  10.     
  11. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
  12.     
  13. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
  14.     
  15. //在需要用户检测的网页里需要增加下面两行  
  16.     
  17. //curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);  
  18.     
  19. //curl_setopt($ch, CURLOPT_USERPWD, US_NAME.”:”.US_PWD);  
  20.     
  21. $contents = curl_exec($ch);  
  22.     
  23. curl_close($ch);  
  24.     
  25. echo $contents;  
  26.     
  27. ?>  

 

3.fopen->fread->fclose

PHP代码
        
  1. <?php  
  2.     
  3. $handle = fopen (”http://www.xxx.com/”, “rb”);  
  4.     
  5. $contents = “”;  
  6.     
  7. do {  
  8.     
  9. $data = fread($handle, 8192);  
  10.     
  11. if (strlen($data) == 0) {  
  12.     
  13. break;  
  14.     
  15. }  
  16.     
  17. $contents .= $data;  
  18.     
  19. while(true);  
  20.     
  21. fclose ($handle);  
  22.     
  23. echo $contents;  
  24.     
  25. ?>  

 


Ps1.使用file_get_contents和fopen必须空间开启allow_url_fopen。方法:编辑php.ini,设置 allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。

Ps2.使用curl必须空间开启curl。

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

Tags: ,
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]