PHP uses fopen and file_get_contents to read file instances

Source: Internet
Author: User
PHP read files can use the fopen and file_get_contents these two functions, there is no essential difference between the first, but the former PHP code to read the file is more complicated than the latter. In this article, we explain the implementation code of fopen and file_get_contents reading files through an example. Need to the code farmers can refer to.

Fopen reads the file in the following code:

 
  PHP$file _name = "1.txt"; Echo $file _name . ""; $fp fopen ($file _name, ' R '); // $buffer =fgets ($fp);  while (! feof ($fp)) {    $bufferfgets($fp);     Echo $buffer ;} fclose ($fp);? >       

Note fopen read files need to be combined with the fgets and fclose functions.

File_get_contents reads the file in the following code:

 
  PHPif (file_exists($path)) {    $bodyfile_get_contents( $path );     Echo $body // Input File Contents  Else  {    echo$path";}? >       

This function reads all the contents of the file at once and displays it, but if the file is super-large it causes PHP to occupy a lot of memory.

Of course, like file This is generally the file read the array, but also can be implemented to read the file

The above describes PHP using fopen and file_get_contents read the file instance, including the content, I hope the PHP tutorial interested in a friend helpful.

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