php提取文本数据 php获取文本内容

想通过PHP实现读取txt文本每次刷新网页随机获取5行数据并输出?$content = file("test.txt");
$randContent = array_rand($content,5);
echo implode("br /",$randContent);
第一行使用file把把整个文件读入一个数组中
第二行使用array_rand在数组中随机取出5个元素
第三行将取出的5个数组中间添加br /标签并打印出来
file
把整个文件读入一个数组中
file ( string $filename , int $flags = 0 , resource $context = ? ) : array
array_rand
从数组中随机取出一个或多个随机键
array_rand ( array $array , int $num = 1 ) : int|string|array
implode
将一个一维数组的值转化为字符串
implode ( string $glue , array $pieces ) : string
如何使用PHP读取文本文件内容利用PHP读取文本文件的内容 , 其实很简单,我们只需要掌握函数“file_get_contents();”的使用就可以了 。下面 , 小编将作详细的介绍 。
工具/原料
电脑一台
WAMP开发环境
方法/步骤
file_get_content()函数介绍 。使用file_get_contents()获取txt文件的内容,具体参数说明如下:
2
具体实例说明 。从文本文件tst.txt中读取里面的内容并显示在浏览器中,具体代码和图示如下:
?php
$file = 'tst.txt';
$content = file_get_contents($file); //读取文件中的内容
echo $content;
?
php如何读取文本指定的内容?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);
}
?
--------第二种方法------------
?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
$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
$file_path = "test.txt";
if(file_exists($file_path)){
$file_arr = file($file_path);
for($i=0;$icount($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("\r\n","br /",$str);
echo $str;
}
?
【php提取文本数据 php获取文本内容】关于php提取文本数据和php获取文本内容的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读