Home >Backend Development >PHP Tutorial >Summary of common methods for reading files in PHP
If the file to be read is not a local ordinary file, but a remote file or stream file, this method cannot be used, because filesize cannot obtain the size of these files. At this point, you need to use the return value of feof() or fread() to determine whether the end of the file has been read. For example:
or:
2. fgets method string fgets ( int $handle [, int $length ] ) fgets() reads a line from the file pointed to by handle and returns a string up to length - 1 bytes long. Stops when a newline character (included in the return value), EOF, or length - 1 bytes has been read (whichever occurs first). If length is not specified, it defaults to 1K, or 1024 bytes.
Note: The length parameter becomes optional from 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 method string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] ) Same function as fgets, but fgetss will try to remove any HTML and PHP tags from the read text. You can use the optional third parameter to specify which tags are not to be removed.
4. file array file ( string $filename [, int $use_include_path [, resource $context ]] ) Read the contents of the file into an array. Each item in the array corresponds to a line in the file, including newlines. You can use the rtrim() function to filter out newline characters when line terminators are not required.
5. readfile method int readfile ( string $filename [, bool $use_include_path [, resource $context ]] ) Read in a file and write to the output buffer. Returns the number of bytes read from the file. Returns FALSE on error and displays an error message unless called as @readfile().
1 2 End of next page Page |