Read specific column in CSV to Array

ayasocool picture ayasocool · Mar 2, 2016 · Viewed 8.5k times · Source

I am trying to read a certain data in my csv file and transfer it to an array. What I want is to get all the data of a certain column but I want to start on a certain row (let say for example, row 5), is there a possible way to do it? What I have now only gets all the data in a specific column, want to start it in row 5 but can't think any way to do it. Hope you guys can help me out. Thanks!

<?php

//this is column C
$col = 2;

// open file
$file = fopen("example.csv","r");

while(! feof($file))
{
    echo fgetcsv($file)[$col];
}

// close connection
fclose($file);

?>

Answer

Chetan Ameta picture Chetan Ameta · Mar 2, 2016

Yes you can define some flag to count the row. Have a look on below solution. It will start printing from 5th row, also you can accesscolum by its index. For eg. for second column you can use $row[1]

$start_row = 5; //define start row
$i = 1; //define row count flag
$file = fopen("myfile.csv", "r");
while (($row = fgetcsv($file)) !== FALSE) {
    if($i >= $start_row) {
        print_r($row);
        //do your stuff
    }
    $i++;
}

// close file
fclose($file);