Question

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);
    }
Was it helpful?

Solution

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.

OTHER TIPS

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);

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top