dongyuedaochen8415 2012-05-20 23:02
浏览 36
已采纳

PHP编写CSV,出于某种原因输出整个网页

function outputCSV($data) {
    $outstream = fopen("php://output", 'w');
    function __outputCSV(&$vals, $key, $filehandler){
        fputcsv($filehandler, $vals, ',', '"');
    }
    array_walk($data, '__outputCSV', $outstream);
    fclose($outstream);
}


function someFunctionInTheBigPHPFile() {
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    $mydata = array(
    array('data11', 'data12', 'data13'),
    array('data21', 'data22', 'data23'),
    array('data31', 'data32', 'data23'));

    outputCSV($mydata);
    exit;
}

The output CSV does contain the data array. The problem is, this array is displayed along with the rest of the webpage, that is everything before this function is called and everything that comes after it, despite these two functions being the only ones that deal with any fopen and writing to files.

How can I stop the rest of the webpage from interfering? I only want the data array in the CSV..

EDIT: I managed to chop off everything succeeding my array by adding exit;, but I still have the problem of the entire website being displayed before the array.

  • 写回答

3条回答 默认 最新

  • dqqvravff05370501 2012-05-21 22:36
    关注

    At the beginning of the PHP file, check straight away if you want to print your CSV (this is probably passed through $_POST or $_GET). If so, run it straight through the function and end that function with an exit;.

    This prevents anything from happening before or after the CSV is created. For some reason all code on the page is included in the new file, even if the file stream was opened and closed at times independant of when the page's content was computed.

    And this effectively leaves you with only what you wanted, not the rubbish before or after it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 hexo+github部署博客
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?