How PHP uses file_get_contents to read large files _php tips

Source: Internet
Author: User
Tags fread

When we encounter a large text file size, such as more than dozens of m or even hundreds of M several g of large files, with Notepad or other editors to open often can not succeed, because they all need to put the contents of the file in memory, then there will be memory overflow and open error, In this case we can use PHP's file read function file_get_contents () for segmented read.

Function description
String file_get_contents (String $filename [, bool $use _include_path [, Resource $context [, int $offset [, int $maxlen] ]]] )
As with file (), only file_get_contents () reads the file into a string. Reads the content of length MaxLen at the location 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. Memory-mapping technology is also used to enhance performance if supported by the operating system.

Application:

Copy Code code as follows:

$str = $content =file_get_contents ("2.sql", false,null,1024*1024,1024);
Echo $str;

You can use the Fread () function if you want to read only segmented reads for smaller files

Copy Code code as follows:

$fp =fopen (' 2.sql ', ' R ');
while (!feof ($fp)) {
$str. =fread ($fp, FileSize ($filename)/10);/Read the file 10 per 1
For processing
}

Echo $str;

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.