V4n1ll4
V4n1ll4

Reputation: 6099

PHP exporting CSV straight to browser

I'm trying to create a CSV export without physically saving the file to the server (so it opens straight in the users browser).

Here's my code. It opens an Excel file fine, but there is only 1 row in the file (i.e. the fields row). There are no rows showing underneath.

Am I looping through my object array correctly?

$fh = fopen('php://output', 'w');

    // Start output buffering (to capture stream contents)
    ob_start();

    fputcsv($fh, $fields);

    // Loop over the * to export
    if(!empty($results)) {
        foreach($results as $row) {
            fputcsv($fh, $row->week_ending);
            fputcsv($fh, $row->project);
            fputcsv($fh, $row->plots);
            fputcsv($fh, $row->categories);
            fputcsv($fh, $row->employee);
        }
    }

    // Get the contents of the output buffer
    $string = ob_get_clean();
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=$filename");
    exit($string);

Result:

Week ending   Project name    Plot numbers    Categories    Employee

Edit

Here are the contents of the object:

Array
(
    [0] => stdClass Object
        (
            [week_ending] => Sunday 10 May 2015
            [project] => Manor Road
            [plots] => 1B, 2B, 3B
            [categories] => 1" Imp Gas, 1"Imp Gas (middle flats)
            [employee] => Your Name
        )

)

Upvotes: 1

Views: 3115

Answers (2)

Harry Mustoe-Playfair
Harry Mustoe-Playfair

Reputation: 1419

Like Matt's answer, fputcsv expects an array as the second parameter. Seeing that each of your $row is an object, we can just typecast it to an array:

<?php

// ...rest of the code... //

foreach($results as $row) {
    fputcsv($fh, (array) $row);
}

This will convert the $row object to an array whose key => value pairs are just the properties of the object.

Upvotes: 3

Matt D.
Matt D.

Reputation: 591

fputcsv has the first argument as a file handle which you have correct. The second argument is supposed to be an array of fields. So without knowing anything more, you should be able to just do:

foreach($results as $row) {
        fputcsv($fh, $row);
    }

Upvotes: 2

Related Questions