array() 中的 CSV 行需要保留换行符
我有一个以下格式的数组 - 它本质上是一个预先格式化的 CSV 行数组 - 本示例中的键 0 和 1 有一个包含换行符的 CSV 值。
Array
(
[0] => 'foo,foo,foo,foo
bar,foo,a:1:{i:0;s:4:"blah";}'
[1] => 'bar,bar,bar,bar
foo,bar,a:1:{i:0;s:4:"blah";}'
[1] => 'bar,bar,bar,foo,bar,a:1:{i:0;s:4:"blah";}'
)
接下来我要做的就是使用 \r\n
作为粘合剂进行内爆,生成 CSV 文件,然后将其写出来。问题是生成的文件不会将包含换行符的字段用双引号括起来,以便可以保留换行符(或者至少我假设它会保留)。
生成的 CSV 文件将上传到数据库或在 Excel 中编辑,并且需要在字段中保留换行符。
在分解为正确的格式后使用 fputcsv 会生成一个 CSV,其中包含换行符并用双引号括起来,可以在记事本或类似文件中查看,但在 Excel 中打开时则不会。
$parent_wholelines = array();
foreach ($output_array as $wholeline) {
$parent_wholelines[] = explode(',', $wholeline);
}
I have an array in the following format - it's essentially an array of preformatted CSV lines - key 0 and 1 in this example have a CSV value containing a line break.
Array
(
[0] => 'foo,foo,foo,foo
bar,foo,a:1:{i:0;s:4:"blah";}'
[1] => 'bar,bar,bar,bar
foo,bar,a:1:{i:0;s:4:"blah";}'
[1] => 'bar,bar,bar,foo,bar,a:1:{i:0;s:4:"blah";}'
)
What I am doing next, is imploding that using \r\n
as the glue, to generate the CSV file, then writing it out. The problem is that the resultant file does not wrap the fields containing a line break in double quotes so that the line break may be preserved (or at least I am assuming it will).
The CSV file generated will be uploaded to a database or edited in Excel and the line breaks need to be preserved in the field.
Using fputcsv after exploding into the right format generates a CSV which has the line break and wrapped in a double quote viewed in Notepad or similar but not when opened in Excel.
$parent_wholelines = array();
foreach ($output_array as $wholeline) {
$parent_wholelines[] = explode(',', $wholeline);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 http://www.php.net/manual/en/function 的一个片段。 fputcsv.php,也许可以帮助你。
或者使用序列化:http://php.net/manual/en/function。序列化.php
One snippet from http://www.php.net/manual/en/function.fputcsv.php, maybe could help you.
OR get a use of serialize: http://php.net/manual/en/function.serialize.php