2014-02-08 176 views
2

我想在php中使用curl庫獲取url的內容。我寫了下面的代碼來做到這一點。即使我沒有在代碼中出現錯誤,輸出中也沒有打印任何內容。由於沒有顯示錯誤消息,我無法弄清楚我做錯了什麼。我試圖打印url響應的詳細信息,如headers, body, time, size, errors(如果有的話)。我使用xampp來運行下面的代碼。使用PHP和Curl獲取URL內容

<?php 
    function url_get_contents($url="google.com",$useragent='cURL',$headers=false, 
    $follow_redirects=false,$debug=false) { 

     # initialise the CURL library 
     $ch = curl_init(); 

     # specify the URL to be retrieved 
     curl_setopt($ch, CURLOPT_URL,$url); 

     # we want to get the contents of the URL and store it in a variable 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 

     # specify the useragent: this is a required courtesy to site owners 
     curl_setopt($ch, CURLOPT_USERAGENT, $useragent); 

     # ignore SSL errors 
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

     # return headers as requested 
     if ($headers==true){ 
      curl_setopt($ch, CURLOPT_HEADER,1); 
     } 

     # only return headers 
     if ($headers=='headers only') { 
      curl_setopt($ch, CURLOPT_NOBODY ,1); 
     } 

     # follow redirects - note this is disabled by default in most PHP installs from 4.4.4 up 
     if ($follow_redirects==true) { 
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
     } 

     # if debugging, return an array with CURL's debug info and the URL contents 
     if ($debug==true) { 
      $result['contents']=curl_exec($ch); 
      $result['info']=curl_getinfo($ch); 
     } 

     # otherwise just return the contents as a variable 
     else $result=curl_exec($ch); 

     # free resources 
     curl_close($ch); 

     # send back the data 
     return $result; 
    } 
?> 

回答

3

您的代碼工作正常。

只需調用該函數即可。

echo url_get_contents(); 

檢查捲曲是否打開。

1

同意上面的答案。另外檢查一下,如果你在瀏覽器中運行它,你可能需要查看頁面的輸出源。