How to read file content in PHP? (Pictures + Videos)

藏色散人
Release: 2018-10-08 09:40:53
Original
9476 people have browsed it

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(&#39;1.txt&#39;,&#39;rb+&#39;);
echo fread($file,filesize(&#39;1.txt&#39;));
fclose($file);
Copy after login

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:

How to read file content in PHP? (Pictures + Videos)

How to read file content in PHP? (Pictures + Videos)

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(&#39;1.txt&#39;);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template