1.file_get_contents
1. <?php 2. $url = http: //www.phpabc.cn/; 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
1. <?php 2. $url = “http: //www.phpabc.cn/”; 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
1. <?php 2. $handle = fopen (”http: //www.phpabc.cn/”, “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。
建议 打开URL时使用file_get_contents()方法,可优化打开速度
Leave a Reply