How to Parse a Text File in PHP

How to Parse a Text File in PHP thumbnail
How to Parse a Text File in PHP

PHP is a server-side language that provides file manipulation functions among its many features. Because of this versatility, there are many ways to approach the goal of parsing a text file. One approach is to parse the file contents into an array, which will set the stage for performing other operations on text files.

Things You'll Need

  • A Web server that supports PHP (for testing)
Show More

Instructions

    • 1

      Open the file for reading by using the "fopen" function. Using fopen binds the file to a stream, which is an abstracted sequence of data. In simplest terms, binding the file to a stream makes it possible to read, write and modify the data.

      <?php

      // Verify that the file exists.

      $path = "list.txt";

      if (file_exists($path))

      {

      $handle = fopen($path, "r");

      }

      ?>

    • 2

      Read the file stream using the "fscanf" function. The "fscanf" function returns portions of the file stream as an array.

      This example shows using the "fscanf" function to read a file stream. The "fscanf" function works best on delimited word lists. It uses a format pattern to interpret the file. Although similar to a regular expression, the format parameter uses its own syntax, which is documented in the PHP "sprintf" function reference topic.

      $format = "%s\t%s\n";

      while ($item = fscanf($handle, $format)) {

      list ($person, $food) = $item;

      echo $item[0] . ": " . $item[1] . "<br />";

      }

      The preceding code example demonstrates parsing a tab-delimited list that contains first names, followed by various items. For example:

      Carlos Toothpaste

      Wendy Cupcakes

      Walter Beans

      Stanley Chips

      The $format variable contains a format pattern "%s\t%s\n", which represents the pattern of the file: two string values "%s" separated by a tab "%t" and followed by a newline character "\n". The resulting array, $item, is set up so that for each line $item[0] contains a name, and $item[1] contains an item.

    • 3

      Close the file stream using the "fclose" function. After file read operation is complete, always use the "fclose" function to close the file stream.

      fclose($handle);

Tips & Warnings

  • There are a few other functions that you can use to open a text file in PHP:

  • The "fgets" function returns one line of the file stream at a time.

  • The "fread" function returns n characters of the file stream.

  • The "file" function reads an entire file into an array.

  • The "file_get_contents" function reads an entire text file into a string.

Related Searches:

Resources

  • Photo Credit Polka Dot RF/Polka Dot/Getty Images

Comments

You May Also Like

Related Ads

Featured