PHP逐行读取txt文件的方法实例

https://blog.csdn.net/Dafei4/article/details/78894768

https://www.cnblogs.com/zuochuang/p/8176868.html

 

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 />';
}

 

<?php
header("content-type:text/html;charset=utf-8");
function readTxt()
{
    # code...
    $handle = fopen("./test.txt", 'rb');

    while (feof($handle)===false) {
        # code...
        yield fgets($handle);
    }

    fclose($handle);
}

foreach (readTxt() as $key => $value) {
    # code...
    echo $value.'<br />';
}

 

$file_path = "0910.txt";
if(file_exists($file_path)) {
    $file_contents = file($file_path);
    for ($i = 0; $i < count($file_contents); $i++) {//逐行读取文件内容
        echo $file_contents[$i]."<br>";
    }
}

最原始的

$file = fopen("test.txt","r");
while(! feof($file))
{
    echo fgets($file). "<br />";
}
fclose($file);

 

https://www.php.cn/php-weizijiaocheng-389370.html

PHP中从实现文件数据的导入导出,可以使用Excel文件,使得数据更加直观,但是操作Excel文件在项目中通常需要依赖PHPExcel类文件,而且执行效率不如txt文本文件。如果数据的列数比较多,而且需要对导出结果进行统计的就是用Excel,如果列数少而且不需要对结果进行过多处理的,可以使用txt文件。

 

PHP实现Excel数据的导入和导出,参看文章:使用PHPExcel实现Excel文件的导入和导出
PHP生成txt文件文件,详见文章:PHP生成txt文件标题及内容

这里,简单实现以下PHP逐行读取txt文件,将读取出txt文件里边的内容,并转化为我们熟悉的数组:

/*

 * 逐行读取TXT文件

 */

function getTxtcontent($txtfile){

    $file = @fopen($txtfile,'r');

    $content = array();

    if(!$file){

        return 'file open fail';

    }else{

        $i = 0;

        while (!feof($file)){

            $content[$i] = mb_convert_encoding(fgets($file),"UTF-8","GBK,ASCII,ANSI,UTF-8");

            $i++ ;

        }

        fclose($file);

        $content = array_filter($content); //数组去空

    }

 

    return $content;

}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章