简体   繁体   English

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

[英]PHP - CSV export - Add comma in column data

I am exporting data to CSV and facing one problem. 我正在将数据导出到CSV并遇到一个问题。

$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. 当我将代码导出为CSV时,它将导出记录,但为category1单独创建一列,为category 2单独创建一列,为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? 我应该怎么做,以逗号分隔的String落在同一列中?

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

You should really take a look at fputcsv . 您应该真正看看fputcsv It does exactly what you want, with different escaping characters and so on. 它具有不同的转义字符等等,完全可以满足您的要求。

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

If you wish to output it to the buffer instead of a file you can use $fh = fopen('php://output', 'w'); 如果您希望将其输出到缓冲区而不是文件中,可以使用$fh = fopen('php://output', 'w'); to write to the client. 写给客户。

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

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