如何更改fputcsv使用的行尾? [英] How can I change the line endings used by fputcsv?

查看:181
本文介绍了如何更改fputcsv使用的行尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个CSV文件,供客户使用

I create a CSV file for download by our client using

$output = fopen('php://output', 'w');

并使用 fputcsv()到客户端下载的CSV文件。

and using fputcsv() to write data to a CSV file which is downloaded by the client.

我在Linux上运行PHP,因此许多Windows应用程序不会解释行尾。

I am running PHP on Linux and consequently the line endings are not interpreted by many Windows applications.

我可以将CSV文件写入服务器上的某个目录,读取并执行 str_replace() \\\
\r\\\
,但这似乎是一个相当笨重的解决问题的方法。有没有办法在不创建物理文件的情况下执行转换?

I could write the CSV file to a directory on the server, read it back in and perform a str_replace() from \n to \r\n, but this seems a rather clunky way of solving the problem. Is there a way to perform the conversion without creating a physical file?

推荐答案

您可以使用流过滤器来完成此操作。这个例子写入一个物理文件,但它应该也适用于 php:// output

You could use stream filters to accomplish this. This example writes to a physical file, but it should work fine for php://output as well.

// filter class that applies CRLF line endings
class crlf_filter extends php_user_filter
{
    function filter($in, $out, &$consumed, $closing)
    {
        while ($bucket = stream_bucket_make_writeable($in)) {
            // make sure the line endings aren't already CRLF
            $bucket->data = preg_replace("/(?<!\r)\n/", "\r\n", $bucket->data);
            $consumed += $bucket->datalen;
            stream_bucket_append($out, $bucket);
        }
        return PSFS_PASS_ON;
    }
}
// register the filter
stream_filter_register('crlf', 'crlf_filter');

$f = fopen('test.csv', 'wt');
// attach filter to output file
stream_filter_append($f, 'crlf');
// start writing
fputcsv($f, array('1 1', '2 2'));
fclose($f);

这篇关于如何更改fputcsv使用的行尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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