PHP File Handling: Reading File
Submitted by joken on Saturday, January 4, 2014 - 13:29.
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
Output:
Output:
Output:
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.php". Then add the following code:
- <?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
- //close the handle
- }
- //we will echo the output here
- echo $content;
- echo '<br/>';
- //this will take each new line and turn it into br tag so that HTML will show it properly
- ?>
hello
hello
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.
- <?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
- //the fread handle using the the filesize it reads
- //how many bytes are you or gets the total number of bytes
- //close the handle
- }
- //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
- ?>
hello
world
But I have here another way using the shortcut for fopen/fread/fclose, and this is also a companion to shortcut file_put_contents(filename, data)
. And here’s add the following code.
- <?php
- //specify the file we want same thing when we writing a file
- $testfile = 'hello.txt';
- //using the shortcut for fopen/fread/fclose
- ?>
hello
world
Add new comment
- 161 views