大飞_dafei

导航

php逐行读取txt文件写入数组的方法

php逐行读取txt文件写入数组的方法

测试数据:

test01
test02
test03
test04
test05
test06
test07
test08
test09
test10
test11
test12

 

方法01

$fileUrl = "E:\web\log.txt";

$isss=file_exists($fileUrl) or exit("There is no file");

$file = fopen($fileUrl, "r") ;

$user=array();
$i=0;
//输出文本中所有的行,直到文件结束为止。
while(! feof($file))
{
    $user[$i]= fgets($file);//fgets()函数从文件指针中读取一行
    $i++;
}
fclose($file);
$user=array_filter($user);
print_r($user);

 

方法02 使用   yield

header('content-type:text/html;charset=utf-8');

// $fd = fopen("./fei.txt",'a');
// for ($i = 0; $i < 10; $i++) {
//     // file_put_contents('fei.txt', "this is $i "."line".PHP_EOL, FILE_APPEND);
//     fwrite($fd, "this is $i " . "line" . PHP_EOL);
// }
// fclose($fd);

function readText()
{
    $handle = fopen("./fei.txt", 'rb');
    while (feof($handle) === false) {
        yield fgets($handle); //注意这里使用生成器语法,可以读取大文件
    }
    fclose($handle);
}

$readTextCon1 = readText();
foreach ($readTextCon1 as $key => $value) {
    echo $value . '<br />';
}

 

其他:

很多时候记录日志需要换行。不建议使用\r\n,因为:

在windows中\r\n是换行
在Mac中\r是换行
在Liunx中\n是换行

但是PHP提供了一个常量来匹配不同的操作系统,即:  PHP_EOL

 

file_put_contents("log.txt", "hello world log.".PHP_EOL, FILE_APPEND);

 

扩展:

 packagist 一个仓库

 PHP版本下载

 PECL___PHP 所有扩展下载

 php-src PHP_扩展下载

PHP数组 函数           PHP字符串 函数

posted on 2017-12-25 17:13  大飞_dafei  阅读(461)  评论(0编辑  收藏  举报