doumi0737
2016-03-22 12:11
浏览 360
已采纳

PHP - CSV导出 - 在列数据中添加逗号

I am exporting data to CSV and facing one problem.

$data['name'] = "Test";
$data['category'] = "category1, category2, caegory3";

When I export code to CSV, it exports records but make separate column for category1, separate column for category 2 and separate column for category3.

Current Output
-------------------------------------------
| Name | Category  |           |           |
-------------------------------------------- 
| TEst | category1 | category2 | category3 |
--------------------------------------------


 Expected Output

------------------------------------------------------------
| Name | Category                      |         |         |
-------------------------------------------- ---------------
| TEst | category1,category2,category3 |         |         |
------------------------------------------------------------

What should I do so comma-separated String fall in same column?

图片转代码服务由CSDN问答提供 功能建议

我将数据导出为CSV并面临一个问题。

  $ data ['name'] =“Test”; 
 $ data ['category'] =“category1,category2,caegory3”; 
   
 
 

当我 将代码导出为CSV,它会导出记录,但会为category1创建单独的列,为category3创建单独的列,为category3创建单独的列。

  Current Output 
 ------  ------------------------------------- \ N | 名称| 类别|  |  | 
 -------------------------------------------- 
 |  TEst |  category1 |  category2 |  category3 | 
 -------------------------------------------- 
  
 
预期输出
 
 ----------------------------------------  -------------------- 
 | 名称| 类别|  |  | 
 -------------------------------------------- ---  ------------ \ N |  TEst |  category1,category2,category3 |  |  | 
 -----------------------------------------------  ------------- 
   
 
 

我应该怎么做才能让逗号分隔的字符串落在同一列中?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dtnd30892 2016-03-22 12:12
    已采纳

    You should have category values between "" so the comma is not interpreted. You can change code like this:

    $data['name'] = 'Test';
    $data['category'] = '"category1, category2, caegory3"';
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dqol6556 2016-03-22 12:17

    You should really take a look at fputcsv. It does exactly what you want, with different escaping characters and so on.

    http://php.net/manual/en/function.fputcsv.php

    If you wish to output it to the buffer instead of a file you can use $fh = fopen('php://output', 'w'); to write to the client.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题