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


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

    测试数据:

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

    方法01

    $fileUrl = "E:weblog.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 />';
    }

    其他:

    很多时候记录日志需要换行。不建议使用
    ,因为:
    
    在windows中
    是换行
    在Mac中
    是换行
    在Liunx中
    是换行
    
    但是PHP提供了一个常量来匹配不同的操作系统,即:  PHP_EOL
    file_put_contents("log.txt", "hello world log.".PHP_EOL, FILE_APPEND);

    扩展:

     packagist 一个仓库

     PHP版本下载

     PECL___PHP 所有扩展下载

     php-src PHP_扩展下载

    PHP数组 函数           PHP字符串 函数

  • 相关阅读:
    追随我心
    开心孕期创业经验和教训总结
    记和老友李吃饭
    如何理解hashCode的作用:
    周计划(2014.08.05~2014.08.10)
    个人职业提升内容
    个人职业发展分析和实现方法
    go 实现的排序算法
    xxx go内置函数
    6.并发
  • 原文地址:https://www.cnblogs.com/dafei4/p/12939188.html
Copyright © 2020-2023  润新知