【轉】用php抓取網頁內容方法總結

php 抓取頁面的內容在實際的開發當中是非常有用的,如作一個簡單的內容採集器,提取網頁中的部分內容等等,抓取到的內容在通過正則表達式做一下過濾就得到了你想要的內容,至於如何用正則表達式過濾,在這裏就不做介紹了,有興趣的同學可以參考本站的《正則表達式》板塊:http://phpzixue.cn/articles11.shtml ,以下就是幾種常用的用php抓取網頁中的內容的方法。
1.file_get_contents
PHP代碼

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

2.curl
PHP代碼
  1. $url = "http://www.phpzixue.cn ";
  2. $ch = curl_init();
  3. $timeout = 5;
  4. curl_setopt($ch, CURLOPT_URL, $url);
  5. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  6. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  7. //在需要用戶檢測的網頁裏需要增加下面兩行
  8. //curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  9. //curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD);
  10. $contents = curl_exec($ch);
  11. curl_close($ch);
  12. echo $contents;
  13. ?>

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

注:
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擴展。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章