技术分享:PHP读取TXT文本内容的五种实用方法

在Web开发中,我们经常需要读取和处理文本文件。PHP作为一种流行的服务器端脚本语言,提供了多种方法来读取TXT文本内容。本文将介绍五种不同的PHP教程,帮助您学习如何使用PHP读取TXT文本内容。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("\r\n","<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("\r\n","<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("\r\n","<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("\r\n","<br />",$str);
echo $str;
fclose($fp);
}
?>

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

相关推荐
你怎么知道我是队长18 分钟前
C语言---循环结构
c语言·开发语言·算法
o0o_-_1 小时前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang
Dxy12393102161 小时前
python把文件从一个文件复制到另一个文件夹
开发语言·python
酷飞飞2 小时前
Qt Designer与事件处理
开发语言·qt·命令模式
天雪浪子2 小时前
Python入门教程之赋值运算符
开发语言·python
Wadli2 小时前
C++语法 | static静态|单例模式
开发语言·c++·单例模式
他们都不看好你,偏偏你最不争气3 小时前
【iOS】AFNetworking
开发语言·macos·ios·objective-c
Bigemap3 小时前
BigemapPro快速添加历史影像(Arcgis卫星地图历史地图)
java·开发语言
进击的_鹏3 小时前
【C++11】initializer_list列表初始化、右值引用和移动语义、可变参数模版等
开发语言·c++
mark-puls3 小时前
C语言打印爱心
c语言·开发语言·算法