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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php //specify the file we want same thing when we writing a file $testfile = 'hello.txt'; //this code is similar to our writing of file if($fh = fopen($testfile, 'r')){ // we are reading $content = fread($fh, 5); //each character is equivalent to 1 byte //close the handle fclose($fh); } //we will echo the output here echo $content; echo ' '; //this will take each new line and turn it into br tag so that HTML will show it properly echo nl2br($content); ?> |
Output:
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php //specify the file we want same thing when we writing a file $testfile = 'hello.txt'; //this code is similar to our writing of file if($fh = fopen($testfile, 'r')){ // we are reading //the fread handle using the the filesize it reads //how many bytes are you or gets the total number of bytes $content = fread($fh, filesize($testfile)); //close the handle fclose($fh); } //we will echo the output here //this will take each new line and turn it into br tag so that HTML will show it properly echo nl2br($content); ?> |
Output:
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 2 3 4 5 6 7 |
<?php //specify the file we want same thing when we writing a file $testfile = 'hello.txt'; //using the shortcut for fopen/fread/fclose $content = file_get_contents($testfile); echo nl2br($content); ?> |
Output:
you are in point of fact a excellent webmaster. The
website loading pace is amazing. It sort of feels that you’re doing any
unique trick. Also, The contents are masterpiece.
you have done a great process in this topic!
I know this website offers quality dependxing postys and extra
material, is here any other website which gives
such stuff in quality?
I bookmark this website right now! Thanks the great deal
to normally the writer for these kinds of a good post.
It reminded me pertaining to https://erin-maloney.com, I believe your present blog
is merely because excellent as their personal.
Permit me surely go back to your page to research
brand new messages inside the future! Best of luck!