Chords
Chords

Reputation: 6850

Create an array of arrays to feed CSV function

I'm trying to create a CSV from a query, and I need the data to fit the following format:

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

$array = array(
    array("data11", "data12", "data13"),
    array("data21", "data22", "data23"),
    array("data31", "data32", "data23"));
outputCSV($array);

I'm used to aggregating data like this:

while ($row = mysql_fetch_array($result)){
    $values[]   = $row['value'];
}

How can I pass outputCSV an appropriate array?

Upvotes: 1

Views: 1180

Answers (3)

Ruben
Ruben

Reputation: 2558

$values = array();

while ($row = mysql_fetch_array($result)) {
    $values[]   = $row;
}

outputCSV($values);

Upvotes: 0

webbiedave
webbiedave

Reputation: 48887

function outputCSV($rows, $fieldNames = array())
{
    if ($fp = fopen('php://output', 'w')) {
        if ($fieldNames) {
            fputcsv($fp, $fieldNames);
        }
        foreach ($rows as $row) {
            fputcsv($fp, $row);
        }
        fclose($fp);
    }
}

Upvotes: 5

eggyal
eggyal

Reputation: 125945

Loop over your $array, calling fputcsv():

foreach ($array as $fields) fputcsv(STDOUT, $fields);

Upvotes: 1

Related Questions