3

I have written the following class to export database results to a CSV file.

<?php
class Export {
    public static function tocsv($results = array(), $fields = array()) {
        $schema_insert = '"'.implode('","', $fields).'"';
        $out .= $schema_insert."\n";

        foreach($results as $row) {
            $schema_insert = '';
            $schema_insert .= '"'.$row->week_ending.'",';
            $schema_insert .= '"'.$row->project.'",';
            $schema_insert .= '"'.$row->employee.'",';
            $schema_insert .= '"'.$row->plots.'",';
            $schema_insert .= '"'.$row->categories.'"';
            $out .= $schema_insert."\n";
        }
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Length: " . strlen($out));
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=$filename");
        echo $out;
        exit;
    }
}
?>

The output is:

"Week ending","Project name","Plot numbers","Categories","Employee"
"Friday 08 May 2015","Big Road","Tracey Smith","1A, 2A, 3A"," Water meter, 1st fix inc lagging"

However, when I open with Excel everything is in one column. Have I missed something?

Thanks.

4
  • try using \n\r instead of \n Commented Apr 29, 2015 at 12:40
  • Thanks, already tried this but same result. Commented Apr 29, 2015 at 12:43
  • why not just use fputcsv ? also where are you defining $filename? Commented Apr 29, 2015 at 12:49
  • Whoops, I forgot to define a filename, it works now. Thanks for pointing that out :) Commented Apr 29, 2015 at 12:54

1 Answer 1

1

Use a semicolon as your fieldterminator instead of a comma, it's an Excel thing really, not a php thing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.