This is an old revision of the document!


Using PHP on CSV Files

You can use PHP to quickly get a column of data from a CSV file. Here's an example CSV format.

  "John", "Doe", "801-555-5555"

PHP has the function fgetcsv() which is great for grabbing data from a CSV file.

Here's an example script where I loop through a CSV file grabbing the 3rd column of information.

<?php

// File and column
$file = 'myfile.csv';
$column = 3;

// Subtract one from the column because fgetcsv is zero based
$column = $column - 1;

// Open the file for reading
if (($handle = fopen($file, "r")) === FALSE) {
    echo "Couldn't open file.";
}

// Loop through the file one CSV line at a time
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    // Output the specified column for this line
    echo $data[$column] . "\n";
}

// Close the file
fclose($handle);

To use that script, simply change the $file value to the file you want to open and the $column value to the column number you want to extract. Save the file as getcol.php and then run it with the following command.

  php getcol.php

The script above only uses memory for one line at a time. As a result, the number of lines it can process is almost unlimited. This is great if you're trying to use a Excel to process a file and getting the “too many rows” error message.

The fgetcsv() function is also very good at parsing quoted data correctly.

comments powered by Disqus
using_php_on_csv_files.1440597811.txt.gz · Last modified: 2020/06/01 22:53 (external edit)