Summary of methods for reading file contents in PHP, _PHP tutorial

WBOY
Release: 2016-07-13 10:09:08
Original
744 people have browsed it

A summary of methods for reading file content in PHP,

The examples in this article summarize the methods of reading file contents in PHP. Share it with everyone for your reference. The details are as follows:

Here are five ways to read file contents in PHP. In actual application, please pay attention to closing fclose($fp);

The first method: fread()

Copy code The code is as follows:
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path,"r");
$str = fread($fp,filesize($file_path));//Specify the read size, here read the entire file content
echo $str = str_replace("rn","
",$str);
}
?>

Second method:
Copy code The code is as follows:
$file_path = "test.txt";
if(file_exists($file_path)){
$str = file_get_contents($file_path);//Read the entire file content into a string
$str = str_replace("rn","
",$str);
echo $str;
}
?>

The third method:
Copy code The code is as follows:
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path,"r");
$str = "";
$buffer = 1024;//Read 1024 bytes each time
while(!feof($fp)){//Loop reading until the entire file is read
$str .= fread($fp,$buffer);
}
$str = str_replace("rn","
",$str);
echo $str;
}
?>

The fourth method:
Copy code The code is as follows:
$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 code The code is as follows:
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path,"r");
$str ="";
while(!feof($fp)){
$str .= fgets($fp);//Read line by line. If fgets does not write the length parameter, the default is to read 1k.
}
$str = str_replace("rn","
",$str);
echo $str;
}
?>

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/947217.htmlTechArticleA summary of methods for reading file content in PHP. This example summarizes the method of reading file content in PHP. Share it with everyone for your reference. The details are as follows: Here is a summary of five ways to read file content in php...
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