在PHP中的CSV生成文件中强制换行 [英] Force new line in CSV generated file in PHP

查看:68
本文介绍了在PHP中的CSV生成文件中强制换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用PHP生成CSV可下载文件.我有一个问题,当我在MS Excell或Ubuntu Libre Office中打开文件时,格式不符合预期.

I am generating a CSV downloadable file in PHP. I have a problem that when I open file in MS Excell or Ubuntu Libre Office the formate is not like what is expected.

我想要这个输出,但是我不能强迫从新行开始.

I want this output but I can not force to start from new line.

Name           Slope   Length   Size(Inches)      Max Length         Location                                       
Name1            5      150       12"                500            location1   
Name2            8      350       12"                400            location 2  
Name3           16      326       12"                400            location3 

这是我的PHP代码

        $csv_data[] = $_POST['name'][$i];
        $csv_data[] = $_POST['slope'][$i];
        $csv_data[] = $_POST['length'][$i];
        $csv_data[] = $size;
        $csv_data[] = $max_length;
        $csv_data[] = $_POST['location'][$i].PHP_EOLE;


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

    $output = fopen('php://output', 'w');
    fputcsv($output, array("Name", "Slope", "Length", "Size", "Max Length", "Location"));
    fputcsv($output, $csv_data);

但是此代码输出如下:

Name    Slope   Length  Size    Max Slope Length    Location                                                
Name1   5   150 12" 500 location1   Name2   8   350 12" 400 location 2  Name3   16  326 12" 400 location3

推荐答案

我所做的是将$csv_data数组设为二维而不是二维,然后使用foreach循环.它有点慢,但为我工作.

What I did is I make the $csv_data array two dimensional instead of one and then I use foreach loop. Its a bit slow but working for me.

这是更新的代码

    $csv_data[$i][] = $_POST['name'][$i];
    $csv_data[$i][] = $_POST['slope'][$i];
    $csv_data[$i][] = $_POST['length'][$i];
    $csv_data[$i][] = $size;
    $csv_data[$i][] = $max_length;
    $csv_data[$i][] = $_POST['location'][$i];

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

    $output = fopen('php://output', 'w');
    fputcsv($output, array("Name", "Slope", "Length", "Size", "Max Length", "Location"));
    foreach ($csv_data as $value) {
        fputcsv($output, $value);
    }

这是我需要的输出.

Name    Slope   Length  Size    Max Length  Location
Name1    5       150    12"        500      location1 
Name2    8       350    12"        400      location12
Name3    16      326    12"        400      location3 
Name4    36      127    12"        400      location4 

这篇关于在PHP中的CSV生成文件中强制换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆