Cakephp CSV帮助器生成前导空间

时间:2018-04-19 19:02:48

标签: php csv cakephp

我正在使用CakePHP CSV帮助程序创建CSV文件。

我总是在列的开头有一个空格。我使用了trimltrim但没有任何作用。

我还添加了ob_startob_end_clean,但没有任何效果。

我的CSV代码是

  <?php

class CsvHelper extends AppHelper {

    var $delimiter = ',';
    var $enclosure = '"';
    var $filename = 'Export.csv';
    var $line = array();
    var $buffer;

    function CsvHelper() {
        $this->clear();
    }

    function clear() {
        $this->line = array();
        $this->buffer = fopen('php://temp/maxmemory:' . (5 * 1024 * 1024), 'r+');
    }

    function addField($value) {
        $this->line[] = $value;
    }

    function endRow() {
        $this->addRow($this->line);
        $this->line = array();
    }

    function addRow($row) {

        fputcsv($this->buffer, $row, $this->delimiter, $this->enclosure);
    }

    function renderHeaders() {
        ob_start();
        header('Content-Encoding:  UTF-16LE');
        header('Content-Type: text/csv; charset=UTF-8');
        header("Content-type:application/vnd.ms-excel");
        header('Content-Disposition: attachment; filename="' . $this->filename . '"');
        header("Pragma: no-cache");
        header("Expires: 0");
        ob_end_clean();
    }

    function setFilename($filename) {
        $this->filename = $filename;
        if (strtolower(substr($this->filename, -4)) != '.csv') {
            $this->filename .= '.csv';
        }
    }

    function render($outputHeaders = true, $to_encoding = null, $from_encoding = "auto") {

        if ($outputHeaders) {
            if (is_string($outputHeaders)) {

                $this->setFilename(trim($outputHeaders));
            }
            $this->renderHeaders();
        }

        rewind($this->buffer);
        $output = stream_get_contents($this->buffer);

        if ($to_encoding) {
            $output = mb_convert_encoding($output, $to_encoding, $from_encoding);
        }

        return $this->output(trim($output));
    }

}

?>

我从这个ctp文件中调用这个帮助程序来下载并生成报告。

<?php
$line = $gen_reports[0]['Report'];
$arrayKeys = array_keys($line);

$this->CSV->addRow($arrayKeys);
echo $this->CSV->render("filename");die;
?>

结果我在第一列始终是一个领先的空间:

screenshot

我怎样摆脱这个空间?

1 个答案:

答案 0 :(得分:1)

不确定是否只有复制粘贴错误,但在CsvHelper打开php标记之前有一个额外的空格,这可能会导致输出缓冲区中的空格。