I have a plain old text file on my server with a different word on each line - e.g: cat dog banana monkey Code (markup): I'll pulling this text file into my script and want to explode it at each new line. But this isn't working... $textfile = './blabla.txt'; $words = explode('\n', file_get_contents($textfile)); Code (markup): Any ideas why? I've also tried \r, but that didn't work.
You can use the file() function to read each line (word, in your case) into an array element. One of the flags to file() tells it to strip trailing newlines. However, this doesn't always work under Windows, so you need to post-filter the array to right trim whitespace from each element. It's easier than it sounds: $words = file('./blabla.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $words = array_map('rtrim',$words); PHP:
Wow! Looks like I should do some reading on the file function, I never knew it could do things like that. Thanks
No problem. file() is one of several oddly and misleadingly named functions in php. It's something you get used to
While it is true that the file function is your better option, I figured that the answer as to why your initial code didn't work may help you in the future... The thing about single quoted strings in PHP is that not only are variables not interpreted, but neither are escape characters. That is to say while "\n" is a string containing a new line character, '\n' is a string containing a backslash followed by the letter 'n'. Hence, if you used "\n" it probably would have worked (for what it's worth, I haven't had my coffee yet and so am only 95% sure of my answer). That's also assuming that you were using UNIX type new lines, as opposed to Windows or Mac new lines...