fread函数基本用法与停止条件
说明
string fread ( int handle, int length )
fread() 用于从文件指针 handle 中读取最多 length 个字节。当达到以下任一条件时,读取操作会立即停止:已读取指定字节数、到达文件末尾(EOF)、对于网络流有新数据包可用,或在打开用户空间流后已读取了 8192 个字节。具体以最先触发的条件为准。
成功时返回读取到的字符串内容;若发生错误则返回 FALSE。
<?php // 获取文件内容并存储为字符串
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize ($filename));
fclose($handle);
?> 警告
在区分二进制文件和文本文件的系统(如 Windows)上,使用 fopen() 打开文件时,mode 参数必须包含 'b' 标志。
<?php $filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize ($filename));
fclose($handle);
?> 警告
当从非普通本地文件(如远程文件、popen() 或 proc_open() 返回的流)读取时,数据会在一个包可用后即停止读取。因此,应将多次读取的数据收集起来合并成大块。
<?php // 适用于 PHP 5 及以上版本
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?> <?php $handle = fopen ("http://www.example.com/", "rb");
$contents = "";
while (!feof($handle)) {
$contents .= fread($handle, 8192);
} }
?> 注意: 若仅需将文件内容读入字符串,推荐使用 file_get_contents(),其性能远优于上述手动循环代码。
额外:
file_get_contents
(PHP 4 >= 4.3.0, PHP 5)
file_get_contents -- 将整个文件读入一个字符串
说明
string file_get_contents ( string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]]]] )
与 file() 类似,但 file_get_contents() 将文件内容直接读入一个字符串。它从参数 offset 指定的位置开始,读取长度为 maxlen 的内容。若失败则返回 FALSE。
file_get_contents() 是将文件内容读入字符串的首选方法。在操作系统支持的情况下,它会利用内存映射技术以提升性能。