定义

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

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

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

 

语法

PHP file_get_contents()函数具有以下语法。

file_get_contents(path,include_path,context,start,max_length)

 

参数

参数 是必须的 描述
path 需要。 要读取的文件
include_path 可选的。 设置为'1'以搜索php.ini中定义的include_path中的文件
context 可选的。 文件句柄的上下文。上下文是一组可以修改流的行为的选项。可以通过使用NULL来跳过。
start 可选的。 在文件中开始读取的位置。
max_length 可选的。 要读取的字节数。

 

返回值

该函数返回读取的数据或失败时为FALSE。

 

注意

此函数可能返回Boolean FALSE,但也可能返回一个非布尔值,如空字符。所以一般使用===运算符测试此函数的返回值。

 

实例

<?php
/*
http://www.manongjc.com/article/1791.html
作者:码农教程
*/

      $filename = \"test.txt\";
      $filestring = file_get_contents($filename);
      if ($filestring) {
             print $filestring;
      } else {
             print \"Could not open $filename.\\n\";
      }
      
      echo file_get_contents(\"test.txt\");
?>

上面的代码生成以下结果。

\"php

 

实例2

以下代码显示了如何获取和输出网站首页的源代码。

<?php
$homepage = file_get_contents(\'http://www.manongjc.com/\');
echo $homepage;
?>

 

实例3

以下代码显示如何将整个文件读入字符串。

<?php
// Create a stream
/*
http://www.manongjc.com/article/1791.html
作者:码农教程
*/
$opts = array(
  \'http\'=>array(
    \'method\'=>\"GET\",
    \'header\'=>\"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(\'http://www.java2s.com/\', false, $context);
?>
收藏 打印