This example summarizes the way PHP reads the contents of a file. Share to everyone for your reference. Specifically as follows:
Here's a summary of five ways PHP reads the contents of a file. In practical application, please pay attention to close fclose ($FP);
The first method: Fread ()
Copy Code code as follows:
<?php
$file _path = "Test.txt";
if (file_exists ($file _path)) {
$fp = fopen ($file _path, "R");
$str = Fread ($fp, FileSize ($file _path))//Specify the read size, which reads the entire contents of the file
echo $str = Str_replace ("\ r \ n", "<br/>", $str);
}
?>
The second method:
Copy Code code as follows:
<?php
$file _path = "Test.txt";
if (file_exists ($file _path)) {
$str = file_get_contents ($file _path)//Read the entire contents of the file into a string
$str = Str_replace ("\ r \ n", "<br/>", $str);
Echo $str;
}
?>
The third method:
Copy Code code as follows:
<?php
$file _path = "Test.txt";
if (file_exists ($file _path)) {
$fp = fopen ($file _path, "R");
$str = "";
$buffer = 1024;//reads 1024 bytes at a time
while (!feof ($fp)) {//loop read until the entire file is read
$str. = Fread ($fp, $buffer);
}
$str = Str_replace ("\ r \ n", "<br/>", $str);
Echo $str;
}
?>
The fourth method:
Copy Code code as follows:
<?php
$file _path = "Test.txt";
if (file_exists ($file _path)) {
$file _arr = file ($file _path);
for ($i =0; $i <count ($file _arr); $i + +) {//Read file content line by row
echo $file _arr[$i]. " <br/> ";
}
/*
foreach ($file _arr as $value) {
echo $value. " <br/> ";
}*/
}
?>
The Fifth method:
Copy Code code as follows:
<?php
$file _path = "Test.txt";
if (file_exists ($file _path)) {
$fp = fopen ($file _path, "R");
$str = "";
while (!feof ($fp)) {
$str. = Fgets ($fp);//Read-by-line. If Fgets does not write the length parameter, the default is to read 1k.
}
$str = Str_replace ("\ r \ n", "<br/>", $str);
Echo $str;
}
?>
I hope this article will help you with your PHP programming.