|
| HOW TO READ FILES INTO AN ARRAY USING THE fgets() FUNCTION IN PHP
Sometimes it might be useful to read data from a file into an array. This can easily be achieved using the fgets() function of PHP as follows:
Example:
<?
$myFile="test.txt";
$fd=fopen($myFile, "r");
while(!feof($fh))
{
$lines[ ]=fgets($fd);
}
fclose($fd);
?>
In the above example, the fgets() function will read from the opened test.txt until it encounters an end of line or end of file, whichever comes first and stops. It then stores each line in array $lines where each line is an element of that array.
PHP also provides a shortcut way of doing the above as follows:
Example:
<?
$myFile="test.txt";
$lines=file($myFile);
?>
The file function file() opens the file and reads each line into array $lines where each line is an element of that array.
|
|