dtgr6303 2016-04-11 20:38
浏览 198
已采纳

PHP - 将CSV文件流式传输到浏览器

I'm having issues getting CSV files to download directly to my browser without storing the files somewhere on my server. I found a tutorial (https://www.perpetual-beta.org/weblog/php-stream-file-direct.html) but I can't seem to get it working!

This is my main function:

public function exportRecord($id) {
    $contest = (string) $this->getContest($id);
    $entries = (array) $this->getEntries($id);

    $filename = sprintf('%1$s-%2$s-%3$s', str_replace(' ', '', $contest['name']), date('Ymd'), date('His'));
    $output = fopen('php://output', 'w');

    ob_start();

    $header = array(
        'First Name',
        'Last Name',
        'Address',
        'City',
        'State',
        'Zip',
        'Phone',
        'Email',
        'Item Purchased',
        'Partner Name',
        'Partner #',
        'Date Entered',
        'Subscribe'
    );

    fputcsv($output, $header);

    foreach ($entries as $entry) {
        fputcsv($output, $entry);
    }

    $string = ob_get_clean();

    header('Pragma: public');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private', false);
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $filename . '.csv";');
    header('Content-Transfer-Encoding: binary');

    exit($string);
}

I am calling the following two functions, which just do queries on my database...

private function getContest($id) {
    $query = sprintf(
        'SELECT name ' .
        'FROM contests ' .
        'WHERE id = %s;',
        $id
    );

    $result = $this->mysql->query($query);
    $response = '';

    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $response = $row;
        }
    } else {
        echo $this->mysql->error;
    }

    return $response;
}

private function getEntries($id) {
    $query = sprintf(
        'SELECT firstName, ' .
            'lastName, ' .
            'CONCAT(address1, ", ", address2), ' .
            'city, ' .
            'state, ' .
            'zip, ' .
            'phone, ' .
            'email, ' .
            'itemPurchased, ' .
            'partnerName, ' .
            'partnerNum, ' .
            'dateEntered, ' .
            'subscribe ' .
        'FROM entries ' .
        'WHERE contestID = %s;',
        $id
    );

    $result = $this->mysql->query($query);
    $response = '';

    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $response[] = $row;
        }
    } else {
        echo $this->mysql->error;
    }

    return $response;
}

I appreciate any help/advice that you'll give! Here is a screenshot, just to give you an idea of what the issue is: Screenshot Thank you!

  • 写回答

2条回答 默认 最新

  • douhuan4699 2016-04-18 18:13
    关注

    I ended up doing this with JS.

                        } else if (action == 'export') {
                        if (result.data !== false) {
                            var data = encodeURIComponent(result.data);
                            var contest = result.contest.trim();
                            var filename = contest + '.csv';
                            var dataUri = 'data:text/csv;charset=utf-8,' + data;
                            var link = document.createElement('a');
    
                            link.setAttribute('href', dataUri);
                            link.setAttribute('download', filename);
                            document.body.appendChild(link);
                            link.click();
    
                            showMessage('Export successfully created!', 'success');
                        } else {
                            showMessage('There are no entries for this contest! Nothing to export...', 'error');
                        }
                    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决