Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Column Headers To a CSV File With PHP

Tags:

php

csv

I am trying to convert a php/mysql generated table into a downloadable csv file. When a user enters search parameters, a call is made to a mysql table and results returned as table.

I used the solution offered in this thread and it works fabulously: Create a CSV File for a user in PHP

I am able to allow users to save or view the results as a csv file. the problem I am having is I'm not sure how to add column headers to the file. For example, the results that are returned are in the following format: $result[x]['office'], $result[x]['user'], etc..., but I also want to add column titles like "Office" and "User" so that anyone looking at the csv file immediately knows what the data means.

This is the function that generates the csv file:

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

function outputCSV($data) {
        $outstream = fopen("php://output", "a");
        function __outputCSV(&$vals, $key, $filehandler) {
            fputcsv($filehandler, $vals); // add parameters if you want
        }
        array_walk($data, "__outputCSV", $outstream);
        fclose($outstream);
    }

I have tried creating the following function, and then calling it right before I call outputCSV, but it is not successful:

function create_file_header()
{       
    $headers = 'Office, User, Tag, Value';
    $fp = fopen("php://output", "w");
    file_put_contents("$file.csv", $headers);
    fclose($fp);
}

Any help is greatly appreciated.

like image 784
Bad Programmer Avatar asked Feb 15 '12 17:02

Bad Programmer


People also ask

How do I add a header to a csv file?

How do I put a header in a CSV file? If your CSV file doesn't have headers, you can add them by simply creating a new first line in the text file and typing in your headers.

What is the purpose of a column header in a csv file?

A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. Initially, the CSV file is converted to a data frame and then a header is added to the data frame. The contents of the data frame are again stored back into the CSV file.


1 Answers

To create headers, you should just prepend a header row array and use fputcsv as normal.

You don't talk about the format of $data, but if it's an associative array you can do this for a generic solution:

function toCSV($data, $outstream) {
    if (count($data)) {
        // get header from keys
        fputcsv($outstream, array_keys($data[0]));
        // 
        foreach ($data as $row) {
            fputcsv($outstream, $row);
        }
    }
}

I'm don't see the benefit of array_walk() over a foreach loop.

like image 58
Francis Avila Avatar answered Oct 13 '22 18:10

Francis Avila