Joseph
Joseph

Reputation: 348

PHP reading csv column into array

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.

Upvotes: 6

Views: 33767

Answers (4)

Goran
Goran

Reputation: 3410

$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]; 
}

Upvotes: 12

user2140111
user2140111

Reputation: 122

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.

Upvotes: 4

deej
deej

Reputation: 2564

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

Upvotes: 2

Nanhe Kumar
Nanhe Kumar

Reputation: 16307

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

Upvotes: 2

Related Questions