PHP逐行读取文件

时间:2016-07-19 19:13:53

标签: php string file fopen fgets

我试图逐行读取文本文件,但它会截断所有空格减少到一个空格的行。有没有办法在不截断额外空格的情况下读入文件?

        # read file
        $myfile = fopen($target_file, "r") or die("Unable to open file!");
        while(!feof($myfile)) {

            # add line to array
            $line[$linenum] = fgets($myfile, 100);

            # display line
            echo $line[$linenum] . "</br></br>";

            # increment counter
            $linenum = $linenum + 1;

        }

1 个答案:

答案 0 :(得分:0)

也许您可能想要尝试使用file_get_contents()preg_split()foreach循环和conditional logic的组合的其他方法。下面的注释代码摘录演示了如何:

    <?php

        // THE FILE TO BE READ:
        $targetFile             = __DIR__ . "/some-file.txt";

        // VEER OFF THE USUAL FILE PROCESSING FUNCTIONS... GO NUTS ;-)
        // GET THE CONTENTS OF THE FILE & STORE IT IN A VARIABLE (IF IT EXISTS)
        $strFileContents        = null;
        $arrFileLines           = array();
        if(file_exists($targetFile)){
            $strFileContents    = file_get_contents($targetFile);
        }

        // EVERY LINE IN A FILE IS TERMINATED BY A NEW LINE CHARACTER (\n): WE KNOW THAT
        // SO WE SPLIT THE CONTENTS OF THE FILE USING THIS KNOWLEDGE...
        if(!is_null($strFileContents)){
            $arrFileLines   = preg_split("#\n#", $strFileContents);

            // NOW LOOP THROUGH EACH LINE AND ECHO THE CONTENT...
            if(!empty($arrFileLines)){
                foreach($arrFileLines as $iLineNumber=>$strLineText){
                    echo $strLineText . "<br /><br />";
                }
            }
        }

希望这提供另一种选择......

干杯,祝你好运......