Today's PHP tip: the file() command
If you want to read the contents of a file into a variable, it is not necessary to use the fopen(), fread(), and fclose() commands.
Instead, take advantage of PHP's file() command, which will read a file into an array which is automatically split on newlines:
$text = file("text.txt");
If you'd rather have the file read into a string variable instead of an array, use the implode() command in conjunction with file() :
$text = implode("", file("text.txt"));
Supposing that the file text.txt contains the following four lines:
This
is
a
test.
...the first example would create $text as an array with four elements, element [0] holding "This\n" and element [3] holding "test."
The second example would create $text as a string, holding the value "This\nis\na\ntest."
Looking for quality PHP scripts at a price that won't break the bank?
Check out
PHP Labs for professional scripts and thousands of webmaster resources.