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字符串 函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值