views:

304

answers:

4

I'm creating a function which can accept a string which is either retrieved through file_get_contents() on a local text file, or something fetched from a url such as http://site.com/338383.txt.

The file will be a tab seperated file, with each item in the file being on its own line. Is it better to use \n or \r to explode() the string and get an array of each line?

I've noticed that in some cases \n doesn't work. I'd like a consistent way which works all the time. Any thoughts?

+5  A: 

You can use file() to get the contents of the file as array with individual lines.

duckyflip
thanks, just what i wanted
Click Upvote
A: 

You can use preg_split () to explode by /\n\r|\n|\r/, and then trim () each item to make sure no trailing whitespace is remaining (if it’s appropriate).

Ilya Birman
+2  A: 

As duckyflip points out, you can use the file() function to get an array of file lines. However, if you still need to explode (for an unknown reason), you should use the PHP constant PHP_EOL instead of '\n' as this is cross-platform compliant.

Kieran Hall
But couldn't you still be reading a file written on a different platform? So in that case PHP_EOL on the server would not necessarily correspond to that in the file?
Tom Haigh
+1  A: 

Problem is that newline is defined differently for different "text/plain" encodings and platforms. The quick-and-dirty solution would probably be to use split and the regular expression "\r\n|\r|\n", however, it may break on some unicode files and it has no sense of "context". I.e. if you have a file where LF (\n) is used as a EOL marker, and there's some CRs there which should have been preserved, the CRs will be split on as well.

Kjetil Jorgensen