Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read specific column in CSV to Array

Tags:

php

fgetcsv

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);

?>
like image 961
ayasocool Avatar asked Mar 02 '16 06:03

ayasocool


2 Answers

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);
like image 84
Chetan Ameta Avatar answered Nov 03 '22 07:11

Chetan Ameta


You have no guarantee that your file exists or you can read it or ....

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. PHP Manual

//this is column C
$col = 2;

// open file
$file = fopen("example.csv","r");
if (!$file) {
    // log your error ....

}
else {
    while( ($row = fgetcsv($file)) !== FALSE){
         if (isset($row[$col])) // field doesn't exist ...
         else                   print_r ($row[$col]);
    }
}

// close file
fclose($file);

?>
like image 35
Halayem Anis Avatar answered Nov 03 '22 09:11

Halayem Anis