php 讀取檔案函數

來源:互聯網
上載者:User

 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;  ?>

聯繫我們

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