繁体   English   中英

PHP CSV列标题

[英]PHP CSV Column Headings

我正在将调查中的一些数据导出到CSV,供另一支使用PHP的团队使用。 我已经将第一行数据作为所有标题输出了。 但是我需要一些标题来跨越2列是所有可能的。

标题正确无误,但我需要在某些标题下添加两个数据单元格。

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=lite-survey-data_'.time().'.csv');

require_once ( dirname(dirname(dirname(dirname(__FILE__)))).'/wp-load.php' );

$content =build_csv_download();
$headings = convert_to_csv($content[0]);
$csv_content = convert_to_csv($content[1]);
$output = fopen('php://output', 'w');
fwrite($output, $headings);
fwrite($output, $csv_content);

有任何想法吗?

标题不可能跨越两列,因为CSV是一种基本格式,它不允许您表示合并的单元格。 但是,如果两列中的第二列没有标题(因此heading,,nextheading ),则在Excel中打开heading时, heading将散布到空白单元格中。

CSV不支持跨列,因此您只需将相同的字段标题放在两列的顶部。 它不是世界上最漂亮的东西,但是CSV也不是世界上最灵活的格式。

CSV不支持列扩展。 某些程序(例如Excel)可能会因缺少标题或其他此类技巧而变得有意义,但这并不能为您提供有效的CSV文件。 参见http://tools.ietf.org/html/rfc4180

在制作CSV数据之前,请使用非有效字符串(例如空格或连字符)将数据连接起来。 基本上,您只是将两个数据列合并为一个。

最简单的方法是使用CONCATdocs )组合数据库中的CONCAT

    SELECT 
        id,
        CONCAT(first_name, " " last_name) AS name,
        email
    FROM 
        users

 /*   Gives these results:
    Array
    (
        [0] => Array
            (
                [id] => 1
                [name] => Bob Someuser
                [email] => bob@example.com
            )

        [1] => Array
            (
                [id] => 2
                [name] => George Anotheruser
                [email] => george@example.com
            )

    )
*/

如果您无法在数据库查询中执行此操作,则可以在发生以下情况后使用array_walkdocs )进行此操作:

$headings = array(
    'First heading',
    'Second heading',
    'Third heading'
);

$one_data = array(
    'First data',
    'Second',
    'data',
    'Third data'
);
$data = array();
for ($x=0;$x<10;$x++)
    $data[] = $one_data;

print 'Before fix:';
print_r($data);

function prepare_array (&$item) {
    $item[1] = $item[1].' '.$item[2];
    unset($item[3]);
}
array_walk($data, "prepare_array");

print '<br><br>After fix:';
print_r($data);

function csv_array (&$item) {
    $item = implode(',', $item);
}
$csv = implode(',', $headings)."\n";
array_walk($data, "csv_array");
$csv .= implode("\n", $data);

print '<br><br>CSV:<br>'.$csv;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM