神语

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

函数stream_context_create:

创建并返回一个文本数据流并应用各种选项,可用于fopen(),file_get_contents()等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。

函数原型:resource stream_context_create ([ array $options [, array $params ]] )

在使用file_get_contents函数的时候,经常会出现超时的情况,在这里要通过查看一下错误提示,看看是哪种错误,比较常见的是读取超时,这种情况大家可以通过一些方法来尽量的避免或者解决。这里就简单介绍两种:

一、增加超时的时间限制

这里需要注意:set_time_limit只是设置你的PHP程序的超时时间,而不是file_get_contents函数读取URL的超时时间。一开始以为set_time_limit也能影响到file_get_contents,后来经测试,是无效的。真正的修改 file_get_contents延时可以用resource $context的timeout参数:

$opts = array(

'http'=>array(

'method'=>"GET",

'timeout'=>60,

)
);
//创建数据流上下文 $context = stream_context_create($opts); $html =file_get_contents('http://weibo.com/sichunlei', false, $context); //fopen输出文件指针处的所有剩余数据: //fpassthru($fp); //fclose()前使用

 

二:file_get_contents() 函数

定义和用法

file_get_contents() 函数把整个文件读入一个字符串中。

和 file() 一样,不同的是 file_get_contents() 把文件读入一个字符串。

file_get_contents() 函数是用于将文件的内容读入到一个字符串中的首选方法。如果操作系统支持,还会使用内存映射技术来增强性能。

例子

<?php

echo file_get_contents("test.txt");

?>

 

输出:

This is a test file with test text.

 

posted on 2013-05-22 19:08  神语  阅读(363)  评论(0编辑  收藏  举报