我试图逐行读取文本文件,但它将行截断到所有空格都减少为一个空格的位置。有没有一种方法可以在不截断额外空间的情况下读取文件?
# 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;
}
也许您可能想尝试使用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 />";
}
}
}
希望这能提供一个替代方案。。。
干杯,祝你好运。。。