首页  >  文章  >  后端开发  >  php file_get_contents函数怎么用

php file_get_contents函数怎么用

藏色散人
藏色散人原创
2019-05-25 10:29:214894浏览

php file_get_contents函数怎么用

php file_get_contents函数怎么用?

作用:把整个文件读入一个字符串中。

语法:

file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] ) : string

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

参数:

filename 要读取的文件的名称。
use_include_path 在PHP 5中,FILE_USE_INCLUDE_PATH可以用于触发包含路径搜索。
context

使用stream_context_create()创建的有效上下文资源。

如果你不需要自定义 context,可以用 NULL 来忽略。

offset

读取在原始流上开始的偏移量。

远程文件不支持查找(偏移量)。尝试在非本地文件上查找可能会使用较小的偏移量,但这是不可预测的,因为它在缓冲流上工作。

maxlen 读取数据的最大长度。默认的读取方式是读取到文件的末尾。请注意,此参数应用于筛选器处理的流。

返回值:

函数返回读取的数据或者在失败时返回 FALSE。

php file_get_contents()函数使用示例

获取网站主页

<?php
$homepage = file_get_contents(&#39;http://www.example.com/&#39;);
echo $homepage;
?>

读取文件的一个部分

<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents(&#39;./people.txt&#39;, NULL, NULL, 20, 14);
var_dump($section);
?>

在包含路径中搜索

<?php
// <= PHP 5
$file = file_get_contents(&#39;./people.txt&#39;, true);
// > PHP 5
$file = file_get_contents(&#39;./people.txt&#39;, FILE_USE_INCLUDE_PATH);
?>

使用上下文

<?php
// Create a stream
$opts = array(
  &#39;http&#39;=>array(
    &#39;method&#39;=>"GET",
    &#39;header&#39;=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents(&#39;http://www.example.com/&#39;, false, $context);
?>

以上是php file_get_contents函数怎么用的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn