PHP file_get_contents() 函数用法及示例 - PHP教程

由网友 大卫 发布 阅读 2

PHP file_get_contents() 函数用法及示例 - PHP教程

PHP Filesystem 参考手册

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

语法

string file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] )

此函数类似于file()函数,不同之处在于,file_get_content()函数返回字符串中的文件,该字符串从指定偏移量开始,最大可达maxlen字节。

参数

参数描述
filename必需。指定要读取的文件。
use_include_path可选。如果您还想在 use_include_path(在 php.ini 中)中搜索文件的话,请设置该参数为 '1'。
context可选。指定文件句柄的环境。context 是一套可以修改流的行为的选项。若使用 NULL,则忽略。
offset可选。指定在文件中开始读取的位置。该参数是 PHP 5.1 中新增的。
maxlen可选。指定读取的字节数。该参数是 PHP 5.1 中新增的。

示例1

<?php
   $file = file_get_contents("/PhpProject/sample.txt", true);
   echo $file;
?>

输出结果

www.div.cn
div.cn

示例2

<?php
   $section = file_get_contents("/PhpProject/sample.txt", NULL, NULL, 4, 10);
   var_dump($section);
?>

输出结果

string(10) "div.cn"

PHP Filesystem 参考手册

PHP fclose() PHP dirname()