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;

}

 

 

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