fputcsv在最后一个元素上添加一行 [英] fputcsv adds a line ending on the last element

查看:91
本文介绍了fputcsv在最后一个元素上添加一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的PHP脚本,可以从数组创建一个csv文件.这是代码示例:

I have a basic PHP script that creates a csv file from an array. Here is an example of the code:

$array = [
    [1,2,3],
    [4,5,6]
];

$handle = fopen('test.csv', 'w');

foreach($array as $v)
    fputcsv($handle, $v);

fclose($handle);

生成的文件在文件末尾总是有一个空行,因为fputcsv不知道这是最后一行.关于如何防止这种情况的任何(简单的)想法?

The resulting file always has a blank line at the end of the file, because fputcsv doesn't know that this is the last line. Any (simple) ideas on how to prevent this?

原来的问题现在不相关了(对我来说,但是也许有人需要这样做).即使在文档末尾,fputcsv也应该添加新行,这是所有csv文件的预期行为.

The original question is now irrelevant (to me, but maybe someone will need to do this). fputcsv is supposed to add a new line, even at the end of the document, and this is the expected behavior of all csv files.

我标记了可以解决原始问题的答案,即使它不再与我相关.

I marked the answer that solves the original question, even though it isn't relevant to me anymore.

因此,在我的上下文中,我需要检查数组的最后一行(或任何一行)是否为NULL(否则PHP将通过一个警告,指出fputcsv的第二个参数为null).如果有人感兴趣,这是我更新的脚本:

So in my context, I needed to check if the last line (or any line) of the array is NULL (otherwise PHP will through up a Warning that fputcsv's 2nd parameter is null). Here is my updated script if anyone is interested:

$array = [
    [1,2,3],
    [4,5,6]
];

$handle = fopen('test.csv', 'w');

foreach($array as $v)
    if($v != NULL)
        fputcsv($handle, $v);

fclose($handle);

推荐答案

我在另一个问题上找到了此解决方案: https://stackoverflow .com/a/8354413/1564018

I found this solution on another question: https://stackoverflow.com/a/8354413/1564018

$stat = fstat($handle);
ftruncate($handle, $stat['size']-1);

我在fputcsv()之后添加了这两行,并删除了最后一个新行字符,并删除了文件末尾的空白行.

I added these two lines after fputcsv() and they removed the last new line character, removing the blank line at the end of the file.

这篇关于fputcsv在最后一个元素上添加一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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