Forum

Yampiz Forum

Sharing let knowledge Spreaded, Reading let spirits growth, Creative let culture extended, Let us
  • 禁止廣告文
  • 知識傳播
  • 閱讀
  • 心靈成長
  • 創作
  • 文化傳承
Forum Dictionary / Programming / 網頁/網站程式 / PHP /

PHP 如何獲取網頁內容

New Subject
Random
Previous
Next
|
PHP 如何獲取網頁內容

1、fopen的使用

代碼如下:

程式項目名稱
  1. /* 原始程式碼 */
  2. <?php
  3. $handle = fopen ("http://example.com/", "rb");
  4. $contents = "";
  5. while (!feof($handle)) {
  6. $contents .= fread($handle, 8192);
  7. }
  8. fclose($handle);
  9. echo $contents; //輸出獲取到得內容。
  10. ?>

對 PHP 5 及更高版本可以使用下面的代碼

程式項目名稱
  1. /* 原始程式碼 */
  2. <?php
  3. $handle = fopen("http://example.com", "rb");
  4. $contents = stream_get_contents($handle);
  5. fclose($handle);
  6. echo $contents;
  7. ?>

但上面的代碼容易出現 failed to open stream: HTTP request failed!錯誤,解決方法

有人說在php.ini中,有這樣兩個選項:allow_url_fopen =on(表示可以通過url打開遠程文件),user_agent="PHP"(表示通過哪種腳本訪問網絡,默認前面有個 " ; " 去掉即可。)重啟服務器。

但是有些還是會有這個警告信息,想用完美的解決還差一步,還得設置php.ini裏面的user_agent,php默認的user_agent是PHP,我們把它改成Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)來模擬瀏覽器就可以了

php.ini
  1. user_agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"

在工作中遇到這個問題,後完美解決,故分享給大家。

2、通過curl來實現

代碼如下:

程式項目名稱
  1. /* 原始程式碼 */
  2. <?php
  3. $url = "http://example.com";
  4. $ch = curl_init();
  5. curl_setopt ($ch, CURLOPT_URL, $url);
  6. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  7. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
  8. $dxycontent = curl_exec($ch);
  9. echo $dxycontent;
  10. ?>

linux下可以使用下面的代碼下載
exec("wget {$url}");

PHP抓取外部資源函數fopen / file_get_contents / curl 的區別

fopen / file_get_contents 每次請求都會重新做DNS查詢,並不對DNS信息進行緩存。
但是CURL會自動對DNS信息進行緩存。對同一域名下的網頁或者圖片的請求只需要一次DNS查詢。
這大大減少了DNS查詢的次數。
所以CURL的性能比fopen / file_get_contents 好很多。

  • Keywords : handle, fopen, contents, user_agent, 程式, 目名稱, 原始程式碼, example, curl_setopt, 代碼如下, fclose, failed, dxycontent, compatible, Windows, DNS查詢, 默認, 錯誤, 重啟服務器, 這大大減少
0 0
2012-04-25T07:28:00+0000


  • Now, you can post comments by Facebook Account when your Yampiz account was logout or unvariable. whatever, we suggest to post comment by Yampiz Account to get more bounds to join new events of Heyxu
Comment
 
Verify
  • Auto Platform
    For better browsing experience, it will auto detects your device to display webpage.
  • Bug Report
    Tell us about the idea, problem and errors you found.
  • Comodo Secure
    The sensitive data transmission adopts by SSL-2048 authenticated encryption.
  • Copyright
    © 2009 YamPiz Digital Inc. & Jaby Group. All rights reserved.
  • Revised Version
    V2.2.061
    03 Aug 2023 (GMT+8)