Resource id #13 when trying to export query result to CSV

时间:2017-06-15 10:32:48

标签: php csv

I have this php function:

function get_download($dbmi, $getid) {

    $stmt = $dbmi->prepare("CALL spStartDownload(?)");
    $stmt->bind_param('i', $getid);
    $stmt->execute();
    $result = $stmt->get_result();

    $fp = fopen('file.csv', 'w');
    while($row = $result->fetch_assoc()) {
      fputcsv($fp, $row);
    }

    fclose($fp);

    $stmt->close(); 

    echo $fp;   
}

I can't figure out why it gives me the Resource id #13 error.

Any help is much appreciated.

1 个答案:

答案 0 :(得分:0)

我用这个新功能解决了这个问题:

function get_download($dbmi, $getid) {

    $stmt = $dbmi->prepare("CALL spStartDownload(?)");
    $stmt->bind_param('i', $getid);
    $stmt->execute();
    $result = $stmt->get_result();

    $fp = fopen('php://output', 'w');
    if ($fp && $result) {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="export.csv"');

        fputcsv($fp, $headers, ";");
        while($row = $result->fetch_assoc()) {
          fputcsv($fp, $row, ";");
        }
    }

    $stmt->close(); 

    echo $fp;   
}