Create CSV file from PHP

2

I want to create an XSV file from PHP. What I want is to be able to create columns and give background color to an element for example. I have the following:

<?php

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

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

function outputCSV($data) {
    $output = fopen("php://output", "w");
    foreach ($data as $row) {
        fputcsv($output, $row); // here you can change delimiter/enclosure
    }
    fclose($output);
}
?>

The file is well generated. What is generated looks like this:

AndIwantittolookthisway(everythingdividedbycolumnandifpossibleabackgroundcolor):

Is there an API that I can use?

    
asked by anonymous 06.08.2014 / 17:04

2 answers

1

I ended up doing the following:

<?php
$table = 'nome_tabela';
$outstr = NULL;

header("Content-Type: application/csv");
header("Content-Disposition: attachment;Filename=cars-models.csv");

$conn = mysql_connect("localhost", "user", "pass");
mysql_select_db("bd",$conn);

// Query database to get column names  
$result = mysql_query("show columns from $table",$conn);
// Write column names
while($row = mysql_fetch_array($result)){
    $outstr.= $row['Field'].';';
}  
$outstr = substr($outstr, 0, -1)."\n";

// Query database to get data
$result = mysql_query("select * from $table",$conn);
// Write data rows
while ($row = mysql_fetch_assoc($result)) {
    $outstr.= join(';', $row)."\n";
}

echo $outstr;
mysql_close($conn);
?>

That is, I have to insert the ";" to create a new column instead of having a ",". Now the question of having the line with color is missing.

    
06.08.2014 / 18:29
0

You just need to set the Delimiter field in the fputcsv function

CSV separates each column through the character;

In this case you have to define the function's delimiter to be ";"

fputcsv($output, $row, ";");

The command to execute what you want looks like this:

function outputCSV($data) {
    $output = fopen("php://output", "w");
    foreach ($data as $row) {
        fputcsv($output, $row, ";"); // here you can change delimiter/enclosure
    }
    fclose($output);
}
?>
    
23.06.2018 / 06:12