12 – PHP File Handling: Reading File

0
459

In this tutorial I’m going to show how to read back information from files. So before we can read information from a file we need to use a function fopen just to open the file for reading. In this lesson, we’re going to use the “hello.txt” file that we created in the writing of file lesson.

To start in this lesson, we are going to create a new PHP file called readfile. Then add the following code:

  1. <?php
  2. //specify the file we want same thing when we writing a file
  3. $testfile = 'hello.txt';
  4. //this code is similar to our writing of file
  5. if($fh = fopen($testfile, 'r')){// we are reading
  6. $content = fread($fh, 5);//each character is equivalent to 1 byte
  7. //close the handle
  8. fclose($fh);
  9. }
  10. //we will echo the output here
  11. echo $content;
  12. echo '
  13. ';
  14. //this will take each new line and turn it into br tag so that HTML will show it properly
  15. echo nl2br($content);
  16. ?>

 Output:

h1

We have this result because we simply specify the number of characters we want to display, in our case we write five(5) character. But what if we want to read the entire file and you don’t know how many byte the file is. And add the following code for the second example.

  1. <?php
  2.  
  3. //specify the file we want same thing when we writing a file
  4. $testfile = 'hello.txt';
  5.  
  6. //this code is similar to our writing of file
  7.  
  8. if($fh = fopen($testfile, 'r')){// we are reading
  9. //the fread handle using the the filesize it reads
  10. //how many bytes are you or gets the total number of bytes
  11.  
  12. $content = fread($fh, filesize($testfile));
  13.  
  14. //close the handle
  15. fclose($fh);
  16. }
  17. //we will echo the output here
  18. //this will take each new line and turn it into br tag so that HTML will show it properly
  19. echo nl2br($content);
  20.  
  21. ?>

Output:

h2

But I have here another way using the shortcut for fopen/fread/fclose, and this is also a companion to shortcut <code> file_put_contents(filename, data)</code>.  And here’s add the following code.

  1. <?php
  2. //specify the file we want same thing when we writing a file
  3. $testfile = 'hello.txt';
  4. //using the shortcut for fopen/fread/fclose
  5. $content = file_get_contents($testfile);
  6. echo nl2br($content);
  7. ?>

 Output:

h3

Facebook Comments
(Visited 33 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here