php獲取網頁內容方法總結

        用php抓取頁面的內容在實際的開發當中是非常有用的,如作一個簡單的內容採集器,提取網頁中的部分內容等等
        抓取到的內容在通過正則表達式做一下過濾就得到了你想要的內容,至於如何用正則表達式過濾,在這裏就不做介紹了,有興趣的,以下就是幾種常用的用php抓取網頁中的內容的方法。

首先舉個自己做過的例子:這個例子是調用大衆點評的接口數據 返回的是XML的數據

  1. $api = 'http://api.dianping.com/Promo.svc/search?'; //接口地址  
  2. $param = array(  
  3.     'cityid'    =>'1',  
  4.     //'shoptype'    =>'',   
  5.     //'keyword'     =>'',   
  6.     //'categoryID'  =>'',   
  7.     //'regionid'    =>'',   
  8.     'type'      =>'0',  
  9.     //'range'       =>'',   
  10.     //'order'       =>'',   
  11.     //'lat'         =>'',   
  12.     //'lng'         =>'',   
  13.     //'distance'    =>'',   
  14.     //'page'        =>'',   
  15.       'maxrows'     =>'5',  
  16.       'apikey'      =>'xxxxxxxxxxx',  
  17. ); //這個就是該接口需要的三個參數。   
  18. $query = http_build_query($param);//把參數生成格式  
  19. $url=$api.$query;//合併成最後URL  
  20.   
  21. //$content=file_get_contents($url);  
  22. $contents=file($url); //獲得頁面的源代碼  
  23. //print_r($contents);   
  24. //echo "<hr/>";   
  25. $content=$contents[0];  
  26. $xml = simplexml_load_string($content);  
  27. $lists=$xml ->Promos->Promo;  

這樣獲得內容!

下面是常用的獲取頁面的內容的方法 

1.file_get_contents
PHP代碼 

  1. <?php   
  2. $url = "http://www.jb51.net";   
  3. $contents = file_get_contents($url);   
  4. //如果出現中文亂碼使用下面代碼    
  5. //$getcontent = iconv("gb2312", "utf-8",$contents);   
  6. echo $contents;   
  7. ?>   

2.curl
PHP代碼 

  1. <?php   
  2. $url = "http://www.jb51.net";   
  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
PHP代碼 

  1. <?php   
  2. $handle = fopen ("http://www.jb51.net""rb");   
  3. $contents = "";   
  4. do {   
  5. $data = fread($handle, 1024);   
  6. if (strlen($data) == 0) {   
  7. break;   
  8. }   
  9. $contents .= $data;   
  10. while(true);   
  11. fclose ($handle);   
  12. echo $contents;   
  13. ?>   

 

注:
1.使用file_get_contents和fopen必須空間開啓allow_url_fopen。方法:編輯php.ini,設置 allow_url_fopen = On,allow_url_fopen關閉時fopen和file_get_contents都不能打開遠程文件。
2.使用curl必須空間開啓curl。方法:windows下修改php.ini,將extension=php_curl.dll前面的分號去掉,而且需要拷貝ssleay32.dll和libeay32.dll到C:/WINDOWS/system32下;Linux下要安裝curl擴展。

 

點擊查看原文
發佈了4 篇原創文章 · 獲贊 12 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章