• 源码铺子 欢迎您

分享PHP读取TXT文本内容的五种教程

分类:技术教程 时间:2023-05-01 12:31 浏览:165
概述
正文:PHP读取文件内容在实际开发当中,还是比较常见的,所以今天我就给大家分享几种读取的方法,大家可以选择一种最适合的就行了。第一种,使用fread函数:<?php $file_path = "test.txt"; if(file_exists($file_path)){ $fp = fopen($file_path,"r"); $str&nb
内容

正文:

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("
","<br />",$str);
fclose($fp);
}
?>

第二种,用file_get_contents函数:

<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
$str = str_replace("
","<br />",$str);
echo $str;
}
?>

第三种,用fopen函数:

<?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("
","<br />",$str);
echo $str;
fclose($fp);
}
?>

第四种方法,使用file函数:

<?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 />";
fclose($file_arr);
}
}
?>

第五种,还是使用fopen函数:

<?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("
","<br />",$str);
echo $str;
fclose($fp);
}
?>

好了,以上就是本篇文字为大家介绍的五种方法,当然,开启资源后,记得使用fclose($fp);关闭一下,不然的话,会消耗服务器的资源。

评论
资讯正文页右侧广告
点击排行
源码铺子
网站首页| 关于我们| 广告合作| 联系我们| 隐私条款| 免责声明| 网站地图
CopyRight ©  2020- 源码铺子-www.shopet.cn源码铺子川公网安备51068202000248号 蜀ICP备20020328号-1
本站所有资源来源于互联网,仅用于学习及参考使用,切勿用于商业用途,如产生法律纠纷本站概不负责!
资源除标明原创外均来自网络转载,版权归原作者所有,若侵犯到您权益请联系我们删除,我们将及时处理!若您需使用非免费的软件或服务,请购买正版授权并合法使用!
浏览记录
联系客服
平台客服1 平台客服2 工作时间
09:00 - 21:00
手机版
源码铺子
扫一扫进手机版
返回顶部