《PHP學習:PHP讀取文件內容的五種方式》要點:
本文介紹了PHP學習:PHP讀取文件內容的五種方式,希望對您有用。如果有疑問,可以聯系我們。
PHP學習php讀取文件內容的五種方式
PHP學習分享下php讀取文件內容的五種辦法:好吧,寫完后發現文件全部沒有關閉.實際應用當中,請注意關閉 fclose($fp);
--
PHP學習php讀取文件內容:
PHP學習-----第一種辦法-----fread()--------
PHP學習
<?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("\r\n","<br />",$str);
}
?>
PHP學習--------第二種辦法------------
PHP學習
<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$str = file_get_contents($file_path);//將整個文件內容讀入到一個字符串中
$str = str_replace("\r\n","<br />",$str);
echo $str;
}
?>
PHP學習-----第三種辦法------------
PHP學習
<?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("\r\n","<br />",$str);
echo $str;
}
?>
PHP學習-------第四種辦法--------------
PHP學習
<?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學習----第五種辦法--------------------
PHP學習
<?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("\r\n","<br />",$str);
echo $str;
}
?>
PHP學習以上內容給年夜家分享了PHP讀取文件內容的五種方式,希望年夜家喜歡.
歡迎參與《PHP學習:PHP讀取文件內容的五種方式》討論,分享您的想法,維易PHP學院為您提供專業教程。