6

I there a php function that enables me to read a csv column (COLUMN NOT LINE) into an array or a string ?

thank you in advance.

1
  • 1
    Read the line then keep only the column you are interested in? Also, "into an array or a string" does not make sense. Arrays and strings represent different things.
    – Jon
    Jul 15, 2013 at 12:11

4 Answers 4

9
$csv = array_map("str_getcsv", file("data.csv")); 
$header = array_shift($csv); 
// Seperate the header from data

$col = array_search("Value", $header, true); 
 foreach ($csv as $row) {      
 $array[] = $row[$col]; 
}
2
  • 1
    keep in mind that if you use something that's not in your file as the first argument in array_search, you'll still get the first 'column'
    – adam rowe
    Jul 11, 2018 at 16:59
  • @Goran what is "Value" and why are you searching for it?
    – ptrcao
    May 2 at 14:56
4

May this will help. http://www.php.net/manual/de/function.fgetcsv.php Just grab the position of the row for the column you want to have.

2
$arr=array();
$row = -1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);

        $row++;
        for ($c = 0; $c < $num; $c++) {
            $arr[$row][$c]= $data[$c];
        }
    }
    fclose($handle);
}
2

You should give fgetcsv method a try. It lets you read a file line by line and returns associative array. This function is specially for reading from CSV files.

In any case you will have to read each line even if you will have to process just a column.

http://php.net/manual/en/function.fgetcsv.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.