通过 Laravel 8 中的数组导出 CSV

Export CSV tthrough array in Laravel 8

我正在laravel 8中编写以下代码,将数组放入csv中,然后下载。

public function DownloadCustomerCSV(Request $request) {
    $CustomerData = [
        ["firstName" => "test A", "lastName" => "test B"],
        ["firstName" => "test A", "lastName" => "test B"]
    ];
    $columns = array("FirstName", "LastName");
    
    $callback = function() use ($CustomerData, $columns)
    {
        $file = fopen('php://output', 'w');
        fputcsv($file, $columns);

        foreach($CustomerData as $Customer) {
            fputcsv($file, array($Customer["firstName"], $Customer["lastName"]));
        }
        fclose($file);
    };
    
    $headers = array(
        "Content-type" => "text/csv",
        "Content-Disposition" => "attachment; filename=customers.csv",
        "Pragma" => "no-cache",
        "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
        "Expires" => "0"
    );

    return \Response::stream($callback, 200, $headers);
}

无法访问此站点。该网页可能暂时无法访问,也可能已永久移至新网址。

ERR_INVALID_RESPONSE

我错过了什么吗?

我刚刚在全新安装时复制了它,唯一的错误似乎是第 8 行和第 13 行引用了未定义的变量。

如果您在代码的第 8 行和第 13 行将 $customerData 更改为 $customers,一切都会正常工作。