[PHP學習教程]006.擷取網頁內容(URL Content)

來源:互聯網
上載者:User

標籤:

引言:擷取網頁內容是我們實現網頁操作的基本之基本,今天這一講,我們和大家講一下基本請求網頁內容的幾種方法。

我們似乎每天都要做這樣一件事情,開啟一個瀏覽器,輸入網址,斷行符號,一個空白的頁面頓時有了東西,它可能是百度之類的搜尋網頁面,或是一個擠滿了文字和圖片的門戶網站。

我們可以從三個方面理解這個過程,一個是瀏覽器,二個是伺服器,第三個是瀏覽器和伺服器之間通訊的協議。

當然,我們今天不講<網頁請求過程 >

這一次,我們說一下如何用PHP代碼請求網頁內容。

 

擷取網頁內容方法

1.file_get_contents+[請求方式:GET]

<?php $url  = ‘http://do.org.cn‘; $html = file_get_contents($url); echo $html;?> 

 

2.file_get_contents+[請求方式:POST]

無需Cookie操作,則使用以下方式:

<?php $url    = ‘http://do.org.cn/upload.php‘; $data   = http_build_query(array(‘foo‘ => ‘bar‘)); $params = array(    ‘http‘ => array(        ‘method‘  => ‘POST‘,         ‘content‘ => $data,        ‘header‘  =>             "Content-type: application/x-www-form-urlencoded\r\n" .             "Content-Length: " . strlen($data) . "\r\n"    ));$context = stream_context_create($params); $html    = @file_get_contents($url, ‘‘, $context); 

有需Cookie操作,則在$params裡的‘header‘添加下一行(類似如下文):

"cookie:cookie1=c1;cookie2=c2\r\n" ;

 

3.fopen+[請求方式:GET]

<?php// 嘗試開啟網頁$fp = fopen($url, ‘r‘); // 擷取前序資訊$header = stream_get_meta_data($fp);while (!feof($fp)) {     $result .= fgets($fp, 1024); } fclose($fp); // 輸出結果echo "url header: {$header} <br/>"; echo "url body: $result"; ?> 

 

4.fopen+[請求方式:POST]

<?php $data   = http_build_query(array(‘foo1‘ => ‘bar1‘, ‘foo2‘ => ‘bar2‘)); $params = array(     ‘http‘ => array(         ‘method‘  => ‘POST‘,         ‘content‘ => $data,        ‘header‘  => "Content-type: application/x-www-form-urlencoded\r\nCookie:cook1=c3;cook2=c4\r\n" .         "Content-Length: " . strlen($data) . "\r\n"    ));  $context = stream_context_create($params); $fp      = fopen(‘http://do.org.cn/upload.php‘, ‘rb‘, false, $context); $content = fread($fp, 1024);fclose($fp);echo $content; ?>

 

5.fsockopen+[請求方式:GET]

用fsockopen函數開啟網址URL,以GET方式請求完整的資料,包括header和body.

<?php function get_url($url, $cookie=false) {    $url   = parse_url($url);     $query = $url[path]. "?" .$url[query];     echo "Query:" . $query;    $fp = fsockopen($url[host], $url[port] ? $url[port] : 80, $errno, $errstr, 30);     if (!$fp) {         return false;    } else {         $request  = "GET $query HTTP/1.1\r\n";         $request .= "Host: $url[host]\r\n";         $request .= "Connection: Close\r\n";         if ($cookie) {            $request.="Cookie: $cookie\r\n";         }        $request .= "\r\n";         fwrite($fp, $request);         while ([email protected]feof($fp)) {             $result .= @fgets($fp, 1024);         }        fclose($fp);         return $result;     }}// 擷取url的html部分,去掉header function get_html($url, $cookie=false) {    $data = get_url($url, $cookie);     if ($data) {        $body = stristr($data, "\r\n\r\n");         $body = substr($body, 4, strlen($body));         return $body;     }     return false; }?> 

 

6.fsockopen+[請求方式:POST]

用fsockopen函數開啟網址URL,以POST方式請求完整的資料,包括header和body.

<?php function post_url($url, $data, $cookie, $referrer="") {    // parsing the given URL     $url_info = parse_url($url);          // Building referrer     if ($referrer == "") { // if not given use this script as referrer         $referrer = "111";    }          // making string from $data     foreach ($data as $key => $value) {         $values[] = "$key=" . urlencode($value);    }     $data_string = implode("&", $values);          // Find out which port is needed - if not given use standard (=80)     if (!isset($url_info["port"])) {        $url_info["port"] = 80;     }        // building POST-request:     $request .= "POST ".$url_info["path"]." HTTP/1.1\n";     $request .= "Host: ".$url_info["host"]."\n";     $request .= "Referer: $referer\n";     $request .= "Content-type: application/x-www-form-urlencoded\n";     $request .= "Content-length: ".strlen($data_string)."\n";     $request .= "Connection: close\n";     $request .= "Cookie: $cookie\n";     $request .= "\n";     $request .= $data_string."\n";         $fp = fsockopen($url_info["host"], $url_info["port"]);     fputs($fp, $request);     while (!feof($fp)) {         $result .= fgets($fp, 1024);     }    fclose($fp);         return $result; }?>

 

7.curl庫

注意:使用curl庫之前,需要查看一下php.ini是否已經開啟了curl擴充.

<?php $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, ‘http://do.org.cn/‘); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $content = curl_exec($ch); curl_close($ch);  echo $content; ?>

 

 

 

 

本站文章為 寶寶巴士 SD.Team 原創,轉載務必在明顯處註明:(作者官方網站: 寶寶巴士 ) 
轉載自【寶寶巴士SuperDo團隊】 原文連結: http://www.cnblogs.com/superdo/p/4805187.html

 

 

[PHP學習教程]006.擷取網頁內容(URL Content)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.