php訪問url的四種方式


php訪問url的四種方式

1.fopen方式
//訪問指定URL函數

[php]  view plain copy print?在CODE上查看代碼片派生到我的代碼片
  1. function access_url($url) {    
  2.     if ($url=='') return false;    
  3.     $fp = fopen($url, 'r') or exit('Open url faild!');    
  4.     if($fp){  
  5.     while(!feof($fp)) {    
  6.         $file.=fgets($fp)."";  
  7.     }  
  8.     fclose($fp);    
  9.     }  
  10.     return $file;  
  11. }  


2.file_get_contents方式(打開遠程文件的時候會造成CPU飆升。file_get_contents其實也可以post)

[php]  view plain copy print?在CODE上查看代碼片派生到我的代碼片
  1. $content = file_get_contents("http://www.google.com");  


3.curl方式

[php]  view plain copy print?在CODE上查看代碼片派生到我的代碼片
  1. function curl_file_get_contents($durl){  
  2.     $ch = curl_init();  
  3.     curl_setopt($ch, CURLOPT_URL, $durl);  
  4.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 獲取數據返回    
  5.     curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在啟用 CURLOPT_RETURNTRANSFER 時候將獲取數據返回    
  6.     $r = curl_exec($ch);  
  7.     curl_close($ch);  
  8.     return $r;  
  9. }  


4.fsockopen方式(只能獲取網站主頁信息,其他頁面不可以)

[php]  view plain copy print?在CODE上查看代碼片派生到我的代碼片
    1. $fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);     
    2. if (!$fp) {     
    3.     echo "$errstr ($errno)<br />\n";     
    4. else {     
    5.     $out="GET / HTTP/1.1\r\n";     
    6.     $out.="Host: www.example.com\r\n";     
    7.     $out.="Connection: Close\r\n\r\n";     
    8.     fwrite($fp, $out);     
    9.     while (!feof($fp)) {     
    10.         echo fgets($fp, 128);     
    11.     }  
    12.     fclose($fp);     
    13. }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM