php寫入和讀取txt文件?讀取文件内容的五種方式分享下php讀取文件内容的五種方法:好吧,寫完後發現文件全部沒有關閉實際應用當中,請注意關閉 fclose($fp);--,下面我們就來聊聊關于php寫入和讀取txt文件?接下來我們就一起去了解一下吧!
讀取文件内容的五種方式
分享下php讀取文件内容的五種方法:好吧,寫完後發現文件全部沒有關閉。實際應用當中,請注意關閉 fclose($fp);--
php讀取文件内容:
-----第一種方法-----fread()--------
<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path,"r");
$str = fread($fp,filesize($file_path));//指定讀取大小,這裡把整個文件内容讀取出來
echo $str = str_replace("rn","<br />",$str);
}
?>
--------第二種方法------------
<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$str = file_get_contents($file_path);//将整個文件内容讀入到一個字符串中
$str = str_replace("rn","<br />",$str);
echo $str;
}
?>
-----第三種方法------------
<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path,"r");
$str = "";
$buffer = 1024;//每次讀取 1024 字節
while(!feof($fp)){//循環讀取,直至讀取完整個文件
$str .= fread($fp,$buffer);
}
$str = str_replace("rn","<br />",$str);
echo $str;
}
?>
-------第四種方法--------------
<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$file_arr = file($file_path);
for($i=0;$i<count($file_arr);$i ){//逐行讀取文件内容
echo $file_arr[$i]."<br />";
}
/*
foreach($file_arr as $value){
echo $value."<br/>";
}*/
}
?>
----第五種方法--------------------
<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path,"r");
$str ="";
while(!feof($fp)){
$str .= fgets($fp);//逐行讀取。如果fgets不寫length參數,默認是讀取1k。
}
$str = str_replace("rn","<br />",$str);
echo $str;
}
?>
,更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!