使用 PHP 将列标题添加到 CSV 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9298264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:30:51  来源:igfitidea点击:

Add Column Headers To a CSV File With PHP

phpcsv

提问by Bad Programmer

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.

我正在尝试将 php/mysql 生成的表转换为可下载的 csv 文件。当用户输入搜索参数时,会调用一个 mysql 表并将结果作为表返回。

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

我使用了这个线程中提供的解决方案,它工作得非常好: 在 PHP 中为用户创建一个 CSV 文件

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.

我能够允许用户将结果保存或查看为 csv 文件。我遇到的问题是我不确定如何将列标题添加到文件中。例如,返回的结果采用以下格式:$result[x]['office']、$result[x]['user'] 等...,但我也想添加列标题,如“Office”和“User”,以便任何查看 csv 文件的人都能立即知道数据的含义。

This is the function that generates the csv file:

这是生成 csv 文件的函数:

    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:

我尝试创建以下函数,然后在调用 outputCSV 之前调用它,但没有成功:

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.

任何帮助是极大的赞赏。

回答by Francis Avila

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

要创建标题,您应该只添加一个标题行数组并fputcsv照常使用。

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

您不谈论 的格式$data,但如果它是关联数组,您可以为通用解决方案执行此操作:

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 foreachloop.

我看不到的利益array_walk()在一个foreach循环。

回答by hair raisin

Do this before calling outputCSV:

在调用 outputCSV 之前执行此操作:

array_unshift($data, array('Office', 'User', 'Tag', 'Value'));

Or, if the elements of $dataare associative arrays, this would be more dynamic:

或者,如果 的元素$data是关联数组,这将更加动态:

array_unshift($data, array_keys($data[0]));

回答by seanbreeden

Couldn't you just put it in the outputCSV function?

你不能把它放在 outputCSV 函数中吗?

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");

    $headers = 'Office, User, Tag, Value';
    fwrite($outstream,$headers);

    function __outputCSV(&$vals, $key, $filehandler) {
        fputcsv($filehandler, $vals); // add parameters if you want
    }
    array_walk($data, "__outputCSV", $outstream);
    fclose($outstream);
 }

回答by webbiedave

Add an optional $headersparameter to your outputCSVfunction. If your code passes them, they will be prepended to the csv array:

$headers向您的outputCSV函数添加一个可选参数。如果您的代码通过了它们,它们将被添加到 csv 数组中:

outputCSV($data, array('Office', 'User'));

//

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