tags:

views:

81

answers:

4

In php how can I read a text file and get each line into an array?

I found this code which does it somewhat but looks for a = sign and I need to look for a new line

<?PHP
$file_handle = fopen("dictionary.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode('=', $line_of_text);
print $parts[0] . $parts[1]. "<BR>";
}
fclose($file_handle);
?>
A: 

So, use the character for a newline instead of the '='

'\n'
Ed Swangren
A: 

Rather than using '=', use '\n'.

Example (also strips '\r' characters, for files which use '\r\n' as their line delimiter):

<?PHP
$file_handle = fopen("dictionary.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$line_of_text = str_replace('\r', '', $line_of_text);
$parts = explode('\n', $line_of_text);
print $parts[0] . $parts[1]. "<BR>";
}
fclose($file_handle);
?>

Note: This code example won't work on files which use '\r' by itself to specify newlines.

Matthew Iselin
+5  A: 

Use php's file function:

file — Reads entire file into an array

Example:

$lines = file('dictionary.txt');
echo $lines[0]; //echo the first line
karim79
@Karim: you have to sell it. From the function's documentation: "Reads an entire file into an array."
Telemachus
@Telemachus - I'm aware of that, it is what I use 'edit' for.
karim79
@Karim: fair enough (and I was kidding - just my way of saying "This looks like the answer to me...").
Telemachus
@Telemachus - :) that would make your sense of humor similar to mine.
karim79
+8  A: 

Well, you could just replace the '=' with a "\n" if the only difference is that you're looking for a newline.

However, a more direct way would be to use the file() function:

$lines = file("dictionary.txt");

That's all there is to it!

VoteyDisciple