Several ways to read document content in PHP
##1.fread
string fread ( int $handle , int $length )
fread() returns the read string, and returns FALSE if an error occurs.
<?php $filename = "/usr/local/something.txt"; $handle = fopen($filename, "r");//读取二进制文件时,需要将第二个参数设置成'rb' //通过filesize获得文件大小,将整个文件一下子读到一个字符串中 $contents = fread($handle, filesize ($filename)); fclose($handle); ?>
For example:
<?php $handle = fopen('http://www.baidu.com', 'r'); $content = ''; while(!feof($handle)){ $content .= fread($handle, 8080); } echo $content; fclose($handle); ?>
2.fgets
string fgets ( int $handle [, int $length ] )
<?php $handle = fopen('./file.txt', 'r'); while(!feof($handle)){ echo fgets($handle, 1024); } fclose($handle); ?>
Note: The
length parameter becomes optional as of PHP 4.2.0, if omitted, the length of the line is assumed to be 1024. Starting with PHP 4.3, omitting length will continue reading from the stream until the end of the line. If most of the lines in the file are larger than 8KB, specifying the maximum line length in the script is more efficient in utilizing resources. Starting with PHP 4.3 this function is safe for use with binary files. Earlier versions don't.3.fgetss
string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] )
<?php $handle = fopen('./file.txt', 'r'); while(!feof($handle)){ echo fgetss($handle, 1024, '<br>'); } fclose($handle); ?>
4.file
array file ( string $filename [, int $use_include_path [, resource $context ]] )
<?php $a = file('./file.txt'); foreach($a as $line => $content){ echo 'line '.($line + 1).':'.$content; } ?>
The above is the detailed content of How to read document content in php. For more information, please follow other related articles on the PHP Chinese website!