Detailed explanation of three methods of reading files in PHP

巴扎黑
Release: 2023-03-14 20:54:02
Original
3420 people have browsed it
Three methods for php to read file content:

//******************The first reading method*** ******************************
header("content-type:text/html;charset=utf-8");
//文件路径
$file_path="text.txt";
//判断是否有这个文件
if(file_exists($file_path)){
if($fp=fopen($file_path,"a+")){
//读取文件
$conn=fread($fp,filesize($file_path));
//替换字符串
$conn=str_replace("\r\n","<br/>",$conn);
echo $conn."<br/>";
}else{
echo "文件打不开";
}
}else{
echo "没有这个文件";
}
fclose($fp);
Copy after login
//****************** *Second reading method************************************
header("content-type:text/html;charset=utf-8");
//文件路径
$file_path="text.txt";
$conn=file_get_contents($file_path);
$conn=str_replace("\r\n","<br/>",file_get_contents($file_path));
echo $conn;
fclose($fp);
Copy after login
//*** ***************The third reading method, loop reading************************ *****
header("content-type:text/html;charset=utf-8");
//文件路径
$file_path="text.txt";
//判断文件是否存在
if(file_exists($file_path)){
//判断文件是否能打开
if($fp=fopen($file_path,"a+")){
$buffer=1024;
//边读边判断是否到了文件末尾
$str="";
while(!feof($fp)){
$str.=fread($fp,$buffer);
}
}else{
echo "文件不能打开";
}
}else{
echo "没有这个文件";
}
//替换字符
$str=str_replace("\r\n","<br>",$str);
echo $str;
fclose($fp);
读取INI配置文件的函数:
$arr=parse_ini_file("config.ini");
//返回的是数组
echo $arr[&#39;host&#39;]."<br/>";
echo $arr[&#39;username&#39;]."<br/>";
echo $arr[&#39;password&#39;]."<br/>";
Copy after login

The above is the detailed content of Detailed explanation of three methods of reading files in PHP. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!