A summary of how PHP reads the contents of a file,
This article summarizes how PHP reads the contents of a file. Share to everyone for your reference. Specific as follows:
Here is a summary of the five ways PHP reads the contents of a file. In practical application, please pay attention to closing fclose ($FP);
First method: Fread ()
Copy CodeThe code is 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, where the entire contents of the file are read
echo $str = Str_replace ("\ r \ n", "
", $STR);
}
?>
The second method:
Copy CodeThe code is as follows: <?php
$file _path = "Test.txt";
if (file_exists ($file _path)) {
$str = file_get_contents ($file _path);//reads the entire file contents into a string
$str = Str_replace ("\ r \ n", "
", $STR);
Echo $str;
}
?>
The third method:
Copy CodeThe code is as follows: <?php
$file _path = "Test.txt";
if (file_exists ($file _path)) {
$fp = fopen ($file _path, "R");
$str = "";
$buffer = 1024;//1024 bytes per read
while (!feof ($fp)) {//loop read until the entire file is read
$str. = Fread ($fp, $buffer);
}
$str = Str_replace ("\ r \ n", "
", $STR);
Echo $str;
}
?>
The fourth method:
Copy CodeThe code is as follows: <?php
$file _path = "Test.txt";
if (file_exists ($file _path)) {
$file _arr = file ($file _path);
for ($i =0; $i
echo $file _arr[$i]. "
";
}
/*
foreach ($file _arr as $value) {
echo $value. "
";
}*/
}
?>
The Fifth method:
Copy CodeThe code is 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", "
", $STR);
Echo $str;
}
?>
I hope this article is helpful to everyone's PHP programming.
http://www.bkjia.com/PHPjc/947217.html www.bkjia.com true http://www.bkjia.com/PHPjc/947217.html techarticle PHP Read the contents of the method summary, this article summarizes the PHP read file content method. Share to everyone for your reference. The following: summary of PHP read the contents of the file five ...