Home

How to Read CSV Data in PHP for HTML5 and CSS3 Programming

|
|  Updated:  
2017-03-01 16:41:55
HTML5 and CSS3 All-in-One For Dummies
Explore Book
Buy On Amazon

If you’re working with delimited data is PHP for HTML5 and CSS3 programming, you may want to read in the CSV data yourself. It's not too difficult to do. Look over the following code for readContactCSV.php:

Preview of a php file for HTML and CSS.
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>readContactCSV.php</title>
</head>
<body>
 <h1>Contacts</h1>
 <div>
 <?php
  print <<< HERE
  <table border = "1">
  <tr>
   <th>First</th>
   <th>Last</th>
   <th>email</th>
   <th>phone</th>
  </tr>
HERE;
  $data = file("contacts.csv");
  foreach ($data as $line){
  $lineArray = explode("t", $line);
  list($fName, $lName, $email, $phone) = $lineArray;
  print <<< HERE
   <tr>
   <td>$fName</td>
   <td>$lName</td>
   <td>$email</td>
   <td>$phone</td>
   </tr>
HERE;
  } // end foreach
  //print the bottom of the table
  print "</table> n";
 ?>
 </div>
</body>
</html>

In this program, the contents of a CSV file were read and it was displayed in an HTML table. It's not terribly different than reading any other text file, but there are some new twists.

  1. Print the table heading.

    It's easiest to manually print out the table heading with the field names. A simple heredoc will do the job.

    print <<< HERE
    <table border = "1">
     <tr>
     <th>First</th>
     <th>Last</th>
     <th>email</th>
     <th>phone</th>
     </tr>
    HERE;
  2. Load the data into an array.

    PHP has a marvelous tool called file. This function takes a filename as its only input. It then opens that file and places all the contents in an array, placing each line in its own element of the array. There's no need to make a file pointer, or to open or close the file. In this example, the contents of contacts.csv are loaded into an array called $data.

    $data = file("contacts.csv");
  3. Use a foreach loop to step through the contents.

    Now you can walk through the contents of the file with a simple foreach loop. The current line is placed in a variable called $line.

    foreach ($data as $line){
  4. Explode each line into its own array.

    You have got to love a function with a violent name, especially when it's really useful. Use the explode command to separate the line into its component parts.

     $lineArray = explode("t", $line);
  5. Use the list() function to store each element of the array into its own variable.

    You could just use the array, but it's easier to pass the data back to the same variable names you used when creating the program. The list()construct does exactly that. Feed it a bunch of variable names and assign an array to it, and now each element of the array will be assigned to the corresponding variable.

     list($fName, $lName, $email, $phone) = $lineArray;
  6. Print the variables in an HTML table row.

    All the variables fit well in an HTML table, so just print out the current row of the table.

     print <<< HERE
     <tr>
      <td>$fName</td>
      <td>$lName</td>
      <td>$email</td>
      <td>$phone</td>
     </tr>
    HERE;
  7. Clean up your playthings.

    There's a little housekeeping to do. Finish the loop and close up the HTML table. There's no need to close the file because that was automatically done by the file() function.

     } // end foreach
    //print the bottom of the table
    print "</table> n";

These shortcuts — the file() function and list() — make it very easy to work with CSV data. That's one reason this type of data is popular for basic data problems.

The list() construct works only on numerically indexed arrays and assumes that the array index begins at 0. If you want to use the list() function with associative arrays, surround the array variable with the array_values() function. Technically, list() is not a function but a language construct.

The file() function is appealing, but it isn’t perfect for every situation. It’s great as long as the file size is relatively small, but if you try to load in a very large file, you will run into memory limitations. The “line at a time” approach used in readContact.php doesn’t have this problem because there’s only a small amount of data in memory at any given time.

HTML purists tend to freak out whenever they see an HTML table. It's true that HTML tables were once horribly abused as a layout technique, but that doesn't mean they should never be used.

About This Article

This article is from the book: 

About the book author:

Andy Harris earned a degree in Special Education from Indiana University/Purdue University–Indianapolis (IUPUI). He taught young adults with severe disabilities for several years. He also taught himself enough computer programming to support his teaching habit with freelance programming.
Those were the exciting days when computers started to have hard drives, and some computers connected to each other with arcane protocols. He taught programming in those days because it was fun.
Eventually, Andy decided to teach computer science full time, and he still teaches at IUPUI. He lectures in the applied computing program and runs the streaming media lab. He also teaches classes in whatever programming language is in demand at the time. He has developed a large number of online video-based courses and international distance education projects.
Andy has written several books on various computing topics and languages including Java, C#, mobile computing, JavaScript, and PHP/MySQL.
Andy welcomes comments and suggestions about his books. He can be reached at [email protected].