Read in text file line by line php - newline not being detected

二次信任 提交于 2019-11-28 17:13:54
jmucchiello

What's wrong with file()?

foreach (file($fileName) as $name) {
    echo('<tr><td align="center">'.$name.'</td></tr>');
}

From the man page of fgets:

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

Also, have you tried the file function? It returns an array; each element in the array corresponds to a line in the file.

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.

Chris Lutz

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!