fputcsv and newline codes

前端 未结 8 2256
别那么骄傲
别那么骄傲 2020-11-28 10:12

I\'m using fputcsv in PHP to output a comma-delimited file of a database query. When opening the file in gedit in Ubuntu, it looks correct - each record has a line break (no

8条回答
  •  感情败类
    2020-11-28 11:12

    As webbiedave pointed out (thx!) probably the cleanest way is to use a stream filter.

    It is a bit more complex than other solutions, but even works on streams that are not editable after writing to them (like a download using $handle = fopen('php://output', 'w'); )

    Here is my approach:

    class StreamFilterNewlines extends php_user_filter {
        function filter($in, $out, &$consumed, $closing) {
    
            while ( $bucket = stream_bucket_make_writeable($in) ) {
                $bucket->data = preg_replace('/([^\r])\n/', "$1\r\n", $bucket->data);
                $consumed += $bucket->datalen;
                stream_bucket_append($out, $bucket);
            }
            return PSFS_PASS_ON;
        }
    }
    
    stream_filter_register("newlines", "StreamFilterNewlines");
    stream_filter_append($handle, "newlines");
    
    fputcsv($handle, $list, $seperator, $enclosure);
    ...
    

提交回复
热议问题