插件72:用Curl獲取網頁內容

<?php // Plug-in 72: Curl Get Contents
/*
 * 插件說明:
 * 設計插件的目的是當需要讀取網頁內容時,可以用本插件取代file_get_contents()函數。
 * 它接受網頁的URL地址和準備模仿的瀏覽器用戶代理字符串。若調用成功,
 * 返回這個網頁的內容,若調用失敗,返回FALSE。它需要以下參數:
 * $url 網頁的URL地址
 * $agent 瀏覽器的用戶代理字符串。
 */
// This is an executable example with additional code supplied
// To obtain just the plug-ins please click on the Download link

$agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; ' .
         'rv:1.9.1) Gecko/20090624 Firefox/3.5 (.NET CLR ' .
         '3.5.30729)';
$url   = 'http://pluginphp.com';

echo PIPHP_CurlGetContents($url, $agent);

function PIPHP_CurlGetContents($url, $agent)
{
   // Plug-in 72: Curl Get Contents
   //
   // This plug-in fetches a page that may otherwise be
   // forbidden using the file_get_contents() function.
   // It requires the following arguments:
   //
   //    $url:   The URL of the page to fetch
   //    $agent: A typical browser User Agent string

   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL,            $url);
   curl_setopt($ch, CURLOPT_USERAGENT,      $agent);
   curl_setopt($ch, CURLOPT_HEADER,         0);
   curl_setopt($ch, CURLOPT_ENCODING,       "gzip");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
   curl_setopt($ch, CURLOPT_FAILONERROR,    1);
   curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
   curl_setopt($ch, CURLOPT_TIMEOUT,        8);
   $result = curl_exec($ch);
   curl_close($ch);
   return $result;
}

?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章