Search code examples
phpcsvfputcsv

fputcsv more then one column (quotes)


When trying to generate a CSV I wanted to seperate data in multiple columns however I only see data in A1,A2,A3 columns not in b or C.

Any way how to fix this?

I want name X , age X and city X in three seperate columns

This is some example code :

header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
// Disable caching
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // Proxies

function outputCSV($data) {
    $output = fopen($_SERVER['DOCUMENT_ROOT']."/Project_X/trunk/output/test.csv", 'w');
    foreach ($data as $row) {
        fputcsv($output, $row); // here you can change delimiter/enclosure
    }
    fclose($output);
}

outputCSV(array(
    array("name 1", "age 1", "city 1"),
    array("name 2", "age 2", "city 2"),
    array("name 3", "age 3", "city 3")
));

Edit : test function :

$output = fopen($_SERVER['DOCUMENT_ROOT']."/Project_X/trunk/output/test.csv", 'w');
fputcsv($output, array("hallo;123;4"),";"); // here you can change delimiter/enclosure
fclose($output);

Outputs as file : "hallo;123;4" instead of hallo;123;4

Solved with this :

$array = array("hallo;123;4");
$array = str_replace('"', '', $array);
fputcsv($output, $array);

Solution

  • You're getting this issue because the array you are sending to the fputcsv function only has one element.

    If you pass in the array as: array("hallo", "123", "1"), then it will put each array element into the relevant columns.

    the function fputcsv takes and array of individual elements, not a single string of data, and then the separator to use. In your case a semi-colon. The correct usage, using the array above, would be: fputcsv($output, array("hallo", "123", "1"), ';');

    That is: the file handler of the file, the array of individual element, not an array with a concatenated string, and then the separator to use in the file (a comma will be used if nothing is set here).