fputCSV奇怪的行为 [英] fputCSV strange behaviour

查看:71
本文介绍了fputCSV奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fputcsv创建一个csv,但是当我在excel中打开它时,它输出的数据从第三行开始.为什么会这样?

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?

我想使用fputcsv创建一行列标题,最好的方法是什么?

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

推荐答案

因为您正在将数据写入php://output,所以我假设您正在提供要下载的文件?

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.

最常见的罪魁祸首是在脚本中打开<?php标记之前的空白:

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

错误:





<?php
  // Your code here

右:


<?php
  // Your code here

编辑感谢@SDC提醒我,这也适用于您包含的所有文件.对于这些文件,您还需要确保在?>结束标记后没有尾随空格,或者最好完全删除该结束标记,因为脚本无法正常工作.

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.

这篇关于fputCSV奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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