php中几个文件读取函数的贴心功能

1、用file_get_contents或者fopen、file、readfile等函数读取url的时候,会创建一个名为$http_response_header的变量来保存http响应的报头,使用fopen等函数打开的数据流信息可以用stream_get_meta_data来获取。
2、php5中新增的参数context使这些函数更加灵活,通过它我们可以定制http请求,甚至post数据。


示例代码1:

  1. <?php
  2. $html = file_get_contents('http://www.example.com/');
  3. print_r($http_response_header);
  4.  
  5. // or
  6. $fp = fopen('http://www.example.com/', 'r');
  7. print_r(stream_get_meta_data($fp));
  8. fclose($fp);
  9. ?>

示例代码2:

  1. <?php
  2. $data = array ('foo' => 'bar');
  3. $data = http_build_query($data);
  4.  
  5. $opts = array (
  6.     'http' => array (
  7.         'method' => 'POST',
  8.         'header'=> "Content-type: application/x-www-form-urlencoded\r\n" .
  9.                    "Content-Length: " . strlen($data) . "\r\n",
  10.         'content' => $data
  11.     ),
  12. );
  13.  
  14. $context = stream_context_create($opts);
  15. $html = file_get_contents('http://www.example.com', false, $context);
  16.  
  17. echo $html;
  18. ?>

参考:
http://cn.php.net/manual/zh/function.file-get-contents.php
http://cn.php.net/manual/en/function.stream-context-create.php
http://cn.php.net/manual/zh/wrappers.http.php

7 Comments »

  1. bw said,

    July 11, 2008 @ 5:35 pm

    不错

  2. 深空 said,

    July 28, 2008 @ 5:17 pm

    学习了,模拟POST和GET更简单了

  3. 华芳 said,

    January 20, 2009 @ 5:28 pm

    好 谢谢大哥分享

  4. 一路彷徨 said,

    August 10, 2009 @ 2:52 pm

    $data = array(‘id’ => ’1251′);
    $data = http_build_query($data);

    $opts = array(
    ‘http’ => array(
    ‘method’ => “GET”,
    ‘header’ => “Content-type: application/x-www-form-urlencoded\r\nContent-Length: ” . strlen($data) . “\r\n”,
    ‘content’ => $data
    ),
    );

    $context = stream_context_create($opts);

    $optHtml = file_get_contents(‘ http://www.cssrain.cn/article.asp‘,false,$context);
    echo $optHtml;

    这段代码按道理应该是返回 http://www.cssrain.cn/article.asp?id=1251 的内容吧··
    但是为什么输出的却不是呢?

  5. 快播 said,

    March 17, 2010 @ 5:39 pm

    相当实用!!

  6. 爱宁电饼铛价格 said,

    July 11, 2012 @ 8:19 pm

    http://aining.ladytg.com专门支持原创文章

  7. 吴痔革沈 said,

    December 8, 2013 @ 11:13 am

    杭州东方魅力官方博客http://donfangmeili.qzone.qq.com

    欢迎大家积极光顾

    杭州东方魅力官方网址:www.dongfangmeili.cn

RSS feed for comments on this post

Leave a Comment