32

我有一个我编写的 php 函数,它将获取一个文本文件并将每一行列为表中自己的行。

问题是经典的“在我的机器上运行良好”,但当然,当我要求其他人生成我正在寻找的 .txt 文件时,它会继续以 1 行的形式读取整个文件。当我在我的文本编辑器中打开它时,它看起来就像我期望的那样,每行都有一个新名称,但它是换行符或其他东西。

到目前为止,我得出的结论可能与他们在 Mac 系统上使用的任何文本编辑器有关。

这有意义吗?是否有任何简单的方法来检测文本编辑器识别为新行的这个字符并将其替换为 php 可以识别的标准字符?

更新:添加以下行解决了这个问题。

ini_set('auto_detect_line_endings',true);

功能:

function displayTXTList($fileName) {
    if(file_exists($fileName)) {
        $file = fopen($fileName,'r');
        while(!feof($file)) { 
            $name = fgets($file);
            echo('<tr><td align="center">'.$name.'</td></tr>');
        }
        fclose($file);
    } else {
        echo('<tr><td align="center">placeholder</td></tr>');
    }       
}
4

4 回答 4

32

这对你不起作用?

http://us2.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings

于 2009-05-03T19:38:42.773 回答
11

What's wrong with file()?

foreach (file($fileName) as $name) {
    echo('<tr><td align="center">'.$name.'</td></tr>');
}
于 2009-05-03T19:47:35.187 回答
6

fgets的手册页:

注意:如果在读取 Macintosh 计算机上或由 Macintosh 计算机创建的文件时 PHP 不能正确识别行尾,启用auto_detect_line_endings运行时配置选项可能有助于解决问题。

另外,你试过文件功能吗?它返回一个数组;数组中的每个元素对应于文件中的一行。

Edit: if you don't have access to the php.ini, what web server are you using? In Apache, you can change PHP settings using a .htaccess file. There is also the ini_set function which allows changing settings at runtime.

于 2009-05-03T19:42:45.243 回答
5

This is a classic case of the newline problem.

ASCII defines several different "newline" characters. The two specific ones we care about are ASCII 10 (line feed, LF) and 13 (carriage return, CR).

All Unix-based systems, including OS X, Linux, etc. will use LF as a newline. Mac OS Classic used CR just to be different, and Windows uses CR LF (that's right, two characters for a newline - see why no one likes Windows? Just kidding) as a newline.

Hence, text files from someone on a Mac (assuming it's a modern OS) would all have LF as their line ending. If you're trying to read them on Windows, and Windows expects CR LF, it won't find it. Now, it has already been mentioned that PHP has the ability to sort this mess out for you, but if you prefer, here's a memory-hogging solution:

$file = file_get_contents("filename");
$array = split("/\012\015?/", $file); # won't work for Mac Classic

Of course, you can do the same thing with file() (as has already been mentioned).

于 2009-05-03T19:46:12.710 回答