fputCSV strange behaviour

北城以北 提交于 2019-12-08 12:04:22

问题


I am using fputcsv to create a csv but the data it outputs starts on the 3rd row when i open it in excel. Why is this?

I want to create a row of column headers using fputcsv, what is the best way to do this.?

public function indexAction()
    {
        $this->outputCSV();
        //$this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('passport_admin_main', array(), 'passport_admin_main_outofarea');
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        header('Content-Disposition: attachment; filename="OutOfAreaReport.csv"');
        header('Content-type: application/excel');
        readfile('OutOfAreaReport.csv');
    }

    public function outputCSV(){
        $list = array (
                array('aaa', 'saasasbbb', 'ccdddc', 'dddd')
                );
        $fp = fopen('php://output', 'w');

        foreach ($list as $fields) {
            fputcsv($fp, $fields);
        }

        fclose($fp);
    }

回答1:


Because you are writing the data to php://output, I assume you are offering the file for download?

Well, the extra new lines in the file are coming from further up your script, you have already output them.

The most common culprit here is leading white space before the opening <?php tag in your script:

Wrong:




<?php
  // Your code here

Right:

<?php
  // Your code here

EDIT Thanks to @SDC for reminding me that this also applies to any files you have included. For these files you will also need to make sure there is no trailing white space after the closing ?> tag, or preferably remove the closing tag completely, as it is not necessary for the script to work correctly.




回答2:


I know this has been marked as answered but when I ran into a similar problem I had a lot of includes so I added ob_clean; to clear the buffer and it solved the space issue. Example:

public function outputCSV(){

$list = array ( array('aaa', 'saasasbbb', 'ccdddc', 'dddd') );

//add here  
ob_clean;
   $fp = fopen('php://output', 'w');

   foreach ($list as $fields) {
       fputcsv($fp, $fields);
   }

   fclose($fp);

}



来源:https://stackoverflow.com/questions/11972864/fputcsv-strange-behaviour

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!