How to Get a File into Array With PHP Without Errors

By | November 7, 2008

Most of PHP programmers need to work with files. Simple file operations are used day by day and often files contain necessary data we need to deal with. Anything that could be stored in a list where values are delimited with new lines is what we often use.

Let’s take a simple example. We have a file that contains 5 strings and we need to add all these strings to an array in order to work with it some later. So, the file:

sting1
string2
string3
string4
string5

Easy task, isn’t it? What are the ways to create an array with these values?

First solution is to use file() function. That’s good for a file that contains 5 strings, but not so good for 10000 records. The code will be the following:

<?
$array=file(“file.txt”);
?>

That’s the first solution. Let’s take a look at another one. That’s similar to this, but protects you against incorrect new line endings (for example, a file, that was edited on Windows will cause some problems on a Linux machine).

<?
$array=array_map(“trim”, file(“file.txt”));
?>

And finally the third solution I have for this task.

<?
$fs=fopen(“file.txt”, “r”);
$array=array();
while (!feof($fs))
{
$array[]=trim(fgets($fs));
}
?>

The last option is better for any files. Though PHP has many built-in functions, when you’re dealing with a 10Mb file, it is better to use the last solution to prevent server overload.