Read and parse text files with PHP

Read and parse text files with PHP

Quite often, the need pops up to read and parse text files, typically these are plain text or CSV (exports from Excel, MS Access or some other source).

This guide will show you the pest practice for doing so.

Plain text files

We’ll start with some code:

$myFile = "C:\\myphpexamples\\testFile.txt";
$fh = fopen($myFile, "r");
if ( $fh ) {
  while ( !feof($fh) ) {
    $line = fgets($fh);
  }
  fclose($fh);
}

OK, this will do as it says on the tin, it will read the file and each line will be read into $line. The function fgets() will read from the pointer till the next new line/carriage return in the file. For more information on fgets() view the PHP documentation http://www.php.net/manual/en/function.fgets.php.

One thing to note, I have noticed that without the IF statement, fgets seems to ignore when $fh is undefined (i.e., “filename” does not exist). If that happens, it will keep attempting to read from a nonexistent filehandle until the process can be administratively killed or the server hangs, whichever comes first.

The above is’nt very usefull…

So we will change:

$line = fgets($fh);

to:

$line[] = fgets($fh);

What this will now do is create an array of lines! Your text file will now be in an array that you can use for whatever.

Alternativley you might just want the file in one variable. In which case, there is a very usefully cuntion built into php:

$myFile = file_get_contents("C:\\myphpexamples\\testFile.txt");

This simple line will read the entire file into a variable called $myFile. But how will you know if it worked? Well if file_get_contents() failed for some reason, the $myFile will be FALSE otherwise it will contain the contents.

Now you have your file in a variable you can display it, store it n a database or process it… you may even want to do what we done in the above example – split it into an array of lines:

// Get the whole file into a single string
$myFile = file_get_contents("C:\\myphpexamples\\testFile.txt");
// Explode the file contents string by each line
$lines = explode(PHP_EOL, $myFile); // Replace PHP_EOL with "\r\n" or "\n" or "\r" if you like
// Iterate through each line and do what you need with it
foreach ($lines as $line) {
  echo $line;
}

CSV Files

Now. Some exciting stuff! CSV files. This will perhaps be the most usefull part of this wee guide.

$myFile = "C:\\myphpexamples\\testFile.txt";
$fh = fopen($myFile, "r");
if ( $fh ) {
  while(($data = fgetcsv($fh)) !== FALSE) {
    // process
  }
  fclose($fh);
}

OK, now you know the basics, of it I’ll share one final snippet 🙂

This assumes the 1st line in your CSV file is a header row. it will then read each line and store in an associative array, and my final twist is that it will be a multi-dimensional array containing your whole CSV file as an array! Which you can then process however you wish!

$myFile = "C:\\myphpexamples\\testFile.csv";
$fh = fopen($myFile, "r");
if ( $fh ) {
  //the top line is the field names
  $fields = fgetcsv($fh, 4096, ',');
  //loop through one row at a time
  while (($data = fgetcsv($fh, 4096, ',')) !== FALSE) {
    $data = array_combine($fields, $data);
  }
  fclose($fh);
}
foreach($data as $thing) {
  $thing['name'];
}

Well, hope you found this usefull… as always any further help add a comment or join my forum!

Leave a Reply


The reCAPTCHA verification period has expired. Please reload the page.