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. A file I have has the following 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
comments powered by Disqus
using_php_on_csv_files.1440597473.txt.gz · Last modified: 2020/06/01 22:53 (external edit)