How To

How to Read a CSV File in PHP

Contributor
By Kristen Leigh Grubb
eHow Contributing Writer
(0 Ratings)

PHP has a function called fgetcsv that allows you to place the values from a comma separated value (csv) file into an array. The function reads one line (row) at a time, so it must be placed within a loop in order to process an entire file. The function arguments are as follows: resource, length of line, delimiter, enclosure and escape. You should specify the length to be longer than the longest line. Use the delimiter argument if your file uses something other than a comma. If your data is enclosed in single and double quotes, specify that in the enclosure argument. The escape value defaults to "new line", but can be specified as something else.

Difficulty: Easy
Instructions

Things You'll Need:

  • PHP
  1. Step 1

    Open a blank text file in any text editor.

  2. Step 2

    Start your php script with the line: <?php

  3. Step 3

    Set the starting row number with the line: $row = 1;

  4. Step 4

    Open the .csv file to read only with the line: $file=fopen("example.csv", "r");

  5. Step 5

    Start the while loop that will run through the data and place each line into an array:
    while (($data = fgetcsv($file, 8000, ",")) !== FALSE) {

  6. Step 6

    Count the number of fields in each line: $num = count($data);

  7. Step 7

    Start a for loop to print out the data to the screen: for ($x=0; $x < $num; $x++) {

  8. Step 8

    Print the data to the screen and close the for and while loops: echo $data[$c] ."\n";}}

  9. Step 9

    Close the file with the line: fclose($file);

  10. Step 10

    Close the php script: ?>

  11. Step 11

    Save the script with the ".php" extension. The entire script will look like this:
    <?php
    $row = 1;
    $file = fopen("example.csv", "r");
    while (($data = fgetcsv($file, 8000, ",")) !== FALSE) {
        $num = count($data);
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "\n";}}
    fclose($file);
    ?>

References

Post a Comment

Post a Comment
  • Have you done this? Click here to let us know.
I Did This

Related Ads

Tags
Computers
Alexia Petrakos,

Meet Alexia Petrakos eHow's Computers Expert.

Get Free Computers Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy.   en-US

eHow Computers
eHow_eHow Technology and Electronics