This article mainly introduces two methods of using PHP to read file content.
In the previous article [How does PHP write data to a specified file? ] has explained to you the specific method of writing files in PHP. In fact, the operation methods of writing and reading PHP files are similar. If you need it, you can study this article first.
Below we will introduce in detail the two methods of reading file content in PHP.
The first method: fread function
<?php $file=fopen('1.txt','rb+'); echo fread($file,filesize('1.txt')); fclose($file);
Here we first open the 1.txt file through fopen, and then use fread Function Read the contents of txt file.
Note: The first parameter in fread represents the file read, and the second parameter represents the length of the read file.
If we want to read all the contents of the file, we need to use the filesize function to get all the bytes of the file.
Then the result of reading the file content by this method is as follows:
As you can see from the picture The read content is the same as the original file content.
Second method: file_get_contents function
echo file_get_contents('1.txt');
This method is very simple. We directly use the file_get_contents function to read the local file content.
Note: The file_get_contents() function is the preferred method for reading the contents of a file into a string.
This article is about two methods of reading the contents of txt files in PHP. If you want to learn more about PHP, you can follow the PHP video tutorial on the PHP Chinese website. Everyone is welcome to refer to and learn!
The above is the detailed content of How to read file content in PHP? (Pictures + Videos). For more information, please follow other related articles on the PHP Chinese website!