PHP uses file_get_contents to read large files, _php tutorial

Source: Internet
Author: User

PHP uses file_get_contents to read large files,


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

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 a file into a string. Reads the contents of length MaxLen 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 operating system support also uses memory-mapping techniques to enhance performance.

Application:

Copy the 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 only want to fragment read for a smaller file and finish reading this

Copy the Code code as follows:
$fp =fopen (' 2.sql ', ' R ');
while (!feof ($fp)) {
$str. =fread ($fp, FileSize ($filename)/10);//10 1 per read-out file
For processing
}

Echo $str;

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

http://www.bkjia.com/PHPjc/910594.html www.bkjia.com true http://www.bkjia.com/PHPjc/910594.html techarticle PHP uses file_get_contents to read large files, when we encounter a large text file size, such as more than dozens of m or even hundreds of m a few grams of large files, with Notepad or other editor ...

  • 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.