PHP Tip, using fopen(), fread(), and fclose()

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:


…the first example would create $text as an array with four elements, element [0] holding “Thisn” and element [3] holding “test.” The second example would create $text as a string, holding the value “Thisnisnantest.”

Comments are closed.