Home  >  Article  >  Backend Development  >  PHP tutorial file reading tutorial

PHP tutorial file reading tutorial

巴扎黑
巴扎黑Original
2017-08-09 14:44:091220browse

Here we only introduce the more common methods of reading files:

1, file_get_contents, read the contents of a file into a string

// 读取整个文件
if(file_exists($filepath)){  
    // 例如:读取TXT文件
    $str = file_get_contents($filepath);
    // 编码转换
    $str = iconv("gb2312","UTF-8",$str);
}
$filepath: File path

file_exists: Determine whether the file exists

iconv: Convert character encoding

Of course file_get_contents can also accept reading a url and get the url The file content.

2,fopen, the related reading method based on this function

2.1, the commonly used line-by-line reading of files

if(file_exists($filepath)){
    if ($file_handle = fopen($filepath, "r")) {  // 只读方式

        // 逐行读取
        while (!feof($file_handle)) {     
            $str .= fgetss($file_handle).'
'; } fclose($file_handle); } $str = iconv("gb2312","UTF-8",$str); }
fopen : Open a file or url

feof(): Detect whether the file has reached the end

fgetss: Read a line from the open file and filter out html, php tags ( and fgets Same except filter mark)

fclose: Close the file stream

2.2, use fread

fread is suitable for reading information from binary files, you must specify the need to read in The number of bytes.

$fh = fopen("filepath", "rb");
$res= fread($file_handle, 1024);

This code will read 1024 bytes (1kb) of data (fread will not read more than 8192 bytes, 8kb of data).

If the file is too large, it can only be read in a loop, which can be judged based on the filesize function, if(filesize("filepath") > 8192){...}


The above is the detailed content of PHP tutorial file reading tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn