PHP基础之 file_get_contents() 函数

定义和用法

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

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

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

语法

file_get_contents(path,include_path,context,start,max_length)
参数描述
path 必需。规定要读取的文件。
include_path 可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 "1"。
context

可选。规定文件句柄的环境。

context 是一套可以修改流的行为的选项。若使用 null,则忽略。

start 可选。规定在文件中开始读取的位置。该参数是 PHP 5.1 新加的。
max_length 可选。规定读取的字节数。该参数是 PHP 5.1 新加的。

说明

对 context 参数的支持是 PHP 5.0.0 添加的。

提示和注释

注释:本函数可安全用于二进制对象。

例子

<?php
echo file_get_contents("test.txt");
?>

输出:

This is a test file with test text.
 
下面讲述了PHP中file_get_contents高级用法,分享给大家供大家参考。具体分析如下:

首先解决file_get_contents的超时问题,在超时返回错误后就象js中的settimeout那样进行一次尝试,错误超过3次或者5次后就确认为无法连线伺服器而彻底放弃。
这裡就简单介绍两种解决方法:

一、增加超时的时间限制

注意:set_time_limit只是设定你的PHP程式的超时时间,而不是file_get_contents函数读取URL的超时时间。

我一开始以为set_time_limit也能影响到file_get_contents,后来经测试是无效的。真正的修改file_get_contents延时可以用resource $context的timeout参数:

PHP程序代码如下:

1
2
3
4
5
6
7
8
9
10
11
$opts = array(
    'http'=>array(
      'method'=>"GET",
      'timeout'=>60,
    )
);
 
$context = stream_context_create($opts);
 
$html =file_get_contents('http://www.jb51.net', false, $context);
fpassthru($fp);

二、多次尝试

PHP程序代码如下:

1
2
3
4
$cnt=0;
while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE){
   $cnt++;
}

以上方法对付超时已经OK了。接下来演示一下用file_get_contents实现Post,如下:
PHP程序代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function Post($url, $post = null){
    $context = array();
    if (is_array($post)) {
      ksort($post);
 
      $context['http'] = array (
        'timeout'=>60,
        'method' => 'POST',
        'content' => http_build_query($post, '', '&'),
       );
    }
 
    return file_get_contents($url, false, stream_context_create($context));
}
 
$data = array (
    'name' => 'test',
    'email' => 'test@gmail.com',
    'submit' => 'submit',
);
 
echo Post('http://www.jb51.net', $data);

注意文档头的Set_time_out否则整个文档都得超时了。

posted @ 2016-07-28 08:15  JokerJason  阅读(1226)  评论(0编辑  收藏  举报

It's not who you are underneath, it's what you do that defines you

Brick walls are there for a reason :they let us prove how badly we want things