CSV · PHP

How to extract a single column values from CSV file in PHP

Importing data from a CSV file with PHP may mean you need to store or print just the results of a single and specific column of the table. To make an example, in the following case, I need to extract data from “color” column:

fruit, color, price
tomatoes, red, 0.08
oranges, orange, 0.12
bananas, yellow, 0.12

To extract the single color column from the table, fgetcsv PHP function can be used. This function returns each line values from a CSV table. In the loop, changing the value of $c variable, will output results of each line starting from $c variable value. Now remove $num variable and add  $c=0; $c < 1 (if just first column is wanted) [or $c=1; $c < 2 for second column or also $c=0; $c < 2 for first and second columns and so on] prevents to print all the following columns of the table, restricting results to a single column:

FGETCSV Basic Usage (Extracts all columns results line by line):

 <?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>
 FGETCSV COLUMN “1” EXTRACTION (Extracts just first column results):
 <?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < 1; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>
 FGETCSV COLUMN “2” EXTRACTION (Extracts just second column results):
 <?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=1; $c < 2; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>
 FGETCSV COLUMN “3” EXTRACTION (Extracts just third column results):
 <?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=2; $c < 3; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>