How to Read a Tab Delimited File in PHP

Written by steve mcdonnell Google
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Read a Tab Delimited File in PHP
Use the "explode" function to separate tab-delimited data with PHP. (Stockbyte/Stockbyte/Getty Images)

Text files often store data that you want to read and use with a PHP script. These files are typically either comma-delimited, tab-delimited or use a fixed field width. You can read a tab-delimited file into PHP by reading the contents into a variable, splitting the variable into individual lines or records and splitting each individual record into its tab-delimited data elements using the "explode" function.

Skill level:


  1. 1

    Use an editor to create a new PHP file. For example, type:

    nano readtab.php

  2. 2

    Set up the file to allow for HTML output to the screen. Read the contents of the file with PHP into a variable using the "file_get_contents" function. Check the return value to ensure the process was successful. For example, type:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

    <html xmlns="">


    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Read Tab Delimited Data</title>




    $filename = "myfile.dat";

    $contents = file_get_contents($filename);

    if ($contents === false) die("Unable to read data file $filename!");

  3. 3

    Split the variable with the file contents into an array that contains one element for each line in the file. Use the "explode" function to break the lines on the new line character "\n." For example, type:

    $records = explode("\n", $contents);

  4. 4

    Split each line into its individual tab-separated data components by using the "explode" function on each record and breaking the data on the tab character "\t." Print the results to the screen as you parse the data. For example, type:

    for ($i=0; $i<sizeof($records); $i++) {

    echo "<p>Line $i:";

    $data[$i] = explode("\t", $records[$i]);

    foreach ($data[$i] as $element) echo " | $element ";

    echo "</p>";





Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.