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. Commented Jul 15, 2013 at 12:11

4 Answers 4

12
$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]; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

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'
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.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.