探討:php抓取頁面的幾種方法

來源:互聯網
上載者:User
  1. $url='http://t.qq.com';
  2. $lines_array=file($url);
  3. $lines_string=implode('',$lines_array);
  4. echo htmlspecialchars($lines_string);
複製代碼

2. file_get_contents()函數使用file_get_contents和fopen必須空間開啟allow_url_fopen。方法:編輯php.ini,設定 allow_url_fopen = On,allow_url_fopen關閉時fopen和file_get_contents都不能開啟遠程檔案。

  1. $url='http://t.qq.com';
  2. $lines_string=file_get_contents($url);
  3. echo htmlspecialchars($lines_string);
複製代碼

3. fopen()->fread()->fclose()模式

  1. $url='http://t.qq.com';
  2. $handle=fopen($url,"rb");
  3. $lines_string="";
  4. do{
  5. $data=fread($handle,1024);
  6. if(strlen($data)==0) {
  7. break;
  8. }
  9. $lines_string.=$data;
  10. }while(true);
  11. fclose($handle);
  12. echo htmlspecialchars($lines_string);
複製代碼

4. curl方式使用curl必須空間開啟curl。方法:windows下修改php.ini,將extension=php_curl.dll前面的分號去掉,而且需 要拷貝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux下要安裝curl擴充。

  1. $url='http://t.qq.com';
  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. $lines_string=curl_exec($ch);
  8. curl_close($ch);
  9. echo htmlspecialchars($lines_string);
複製代碼

5. fsockopen()函數 socket模式socket模式能否正確執行,也跟伺服器的設定有關係,具體可以通過phpinfo查看伺服器開啟了哪些通訊協定,比如我的本地php socket沒開啟http,只能使用udp測試一下了。

  1. $fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
  2. if (!$fp) {
  3. echo "ERROR: $errno - $errstr
    \n"
  4. } else {
  5. fwrite($fp, "\n")
  6. echo fread($fp, 26)
  7. fclose($fp)
  8. }
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.