1、用file_get_contents或者fopen、file、readfile等函數讀取url的時候,會建立一個名為$http_response_header的變數來儲存http響應的前序,使用fopen等函數開啟的資料流資訊可以用stream_get_meta_data來擷取。
2、php教程5中新增的參數context使這些函數更加靈活,通過它我們可以定製http請求,甚至post資料。
範例程式碼1:
| 代碼如下 |
複製代碼 |
<?php $html = file_get_contents('http://www.111cn.net); print_r($http_response_header); // or $fp = fopen('http://www.example.com', 'r'); print_r(stream_get_meta_data($fp)); fclose($fp); ?> |
範例程式碼2:
| 代碼如下 |
複製代碼 |
<?php $data = array ('foo' => 'bar'); $data = http_build_query($data); $opts = array ( 'http' => array ( 'method' => 'post', 'header'=> "content-type: application/x-www-form-urlencoded " . "content-length: " . strlen($data) . " ", 'content' => $data ), ); $context = stream_context_create($opts); $html = file_get_contents('http://www.example.com', false, $context); echo $html; ?> |
執行個體三
擷取過來以後自動輸出到瀏覽器,我們有沒有其他的方式組織擷取的資訊,然後控制其輸出的內容呢?完全沒有問題,在curl_setopt()函數的參數中,如果希望獲得內容但不輸出,使用curlopt_returntransfer 參數,並設為非0值/true!,完整代碼請看:
<?php // create a new curl resource $ch = curl_init(); // set url and other appropriate options curl_setopt($ch, curlopt_url, “http://www.google.nl/”); curl_setopt($ch, curlopt_returntransfer, true); // grab url, and return output $output = curl_exec($ch); // close curl resource, and free up system resources curl_close($ch); // replace ‘google’ with ‘phpit’ $output = str_replace(’google’, ‘phpit’, $output); // print output echo $output; ?>