0

I have a very basic question about fputcsv.

My goal is to create a csv file where for each row the first column is the key and the second the value. The result of print_r on my table gives something like this Array ( [city_name: London ] => 8000 [city_name: Dublin ] => 8415

I thought i had to use array_keys and array_values like this :

fputcsv ($fp, array_keys($tablepeople)); 
fputcsv ($fp, array_values($tablepeople));

With this code my csv file got this shape : Name1 Name2 Value1 Value2

How can I do to get this one: Name1 Value 1 Name2 Value2

Where name is the key of the array and value the value.

Could you help me please ?

3 Answers3

2

You have to create an array for each line in your CSV file.

$line = array($key, $value);
fputcsv($out, $line);
Bram Verstraten
  • 1,414
  • 11
  • 24
1

As you can see from the man page here http://php.net/fputcsv you can use this function to add a line in a csv file (so all the columns for one row)

Considering that the first parameter is the file pointer and the second is an array with all the values for one line you can create the array like this:

foreach ($tablepeople as $key=>$value)
{
    fputcsv($fp, array($key, $value);
}
mishu
  • 5,347
  • 1
  • 21
  • 39
1
$csv_array = Array();
foreach($tablepeople as $k => $v) {
    $csv_array[] = Array($k, $v);
}
fputcsv($fp, $csv_array);
Ross McLellan
  • 1,872
  • 1
  • 15
  • 19