drutcs7210 2014-05-27 13:18
浏览 15
已采纳

用于CSV写入的一个字段中的新行

I haven't worked that much with csv export, and now I have a problem. I have something like this:

['client']=>
  ['name']=>'John',
  ['surname']=>'Doe',
  ['things']=>
    [0]=>'jacket',
    [1]=>'shoes',
    [2]=>'hat'

And when I parse ti for csv I get

name | surname | things
John | Doe     | jacket, shoes, hat

And I would like to get

name | surname | things
John | Doe     | jacket
                 shoes
                 hat

Is there a way to do it in PHP?

EDIT: I tried this:

$client['things'] = ",".implode(",", $client['things']);

I tried this also

$client['things'] = ",".implode("
", $client['things']);

and this

$client['things'] = ",".implode("", $client['things']);

and it didn't worked properly.

  • 写回答

1条回答 默认 最新

  • dsmvovm27249 2014-05-27 14:35
    关注

    CSV doesn't support nested sets of values.

    Also according with RFC for CSV format:

    Each record is located on a separate line, delimited by a line break (CRLF).

    and

    Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.

    You must exlude unescaped new line separators, commas and quote symbols and I suggest you to use fputcsv() function to generate valid and correct CSV for most programs and libraries.

    E.g.:

    <?php
    $row = array(
        'name' => 'John',
        'surname' => 'Doe',
        'things' => array('jacket', 'shoes', 'hat'),
    );
    $row = array_map(function ($value) {
        return is_array($value) ? implode(',', $value) : $value;
    }, $row);
    $output = fopen('php://output', 'w');
    fputcsv($output, $row);
    

    Outputs: John,Doe,"jacket,shoes,hat" with CRLF ending.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化