php Using file_get_contents to Read Large Files

  • 2021-08-03 09:24:42
  • OfStack

When we encounter large text files, For example, if there are more than 10M or even hundreds of M and G large files, it is often unsuccessful to open them with Notepad or other editors, because they all need to put all the contents of the files into memory, and then memory overflow will occur and opening errors will occur. In this case, we can use PHP's file reading function file_get_contents () for segmented reading.

Function description
string file_get_contents ( string $filename [, bool $use_include_path [, resource $context [, int $offset [, int $maxlen ]]]] )
Like file () 1, except that file_get_contents () reads the file into a string. The content of length maxlen will be read at the position specified by the parameter offset. If it fails, file_get_contents () returns FALSE.

The file_get_contents () function is the preferred method for reading the contents of a file into a string. If supported by the operating system, memory mapping technology will also be used to enhance performance.

Application:


$str = $content=file_get_contents("2.sql",FALSE,NULL,1024*1024,1024);
echo $str;

You can use the fread () function if you only want to read it in sections for smaller files


$fp=fopen('2.sql','r');
while (!feof($fp)){
$str.=fread($fp, filesize ($filename)/10);// Read the file every time 10 Divide 1
// Process
} echo $str;

The above is how to use file_get_contents function to read large files, super simple, the need for small partners to move away directly!


Related articles: