Skip to content

Instantly share code, notes, and snippets.

@1stevengrant
Forked from MrPunyapal/ExportCSV.php
Created October 25, 2023 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1stevengrant/7caa81325df1e77124b2d41362f8152c to your computer and use it in GitHub Desktop.
Save 1stevengrant/7caa81325df1e77124b2d41362f8152c to your computer and use it in GitHub Desktop.
PHP Function to Export Products as CSV (without saving it in server)
<?php
function exportCSV()
{
// Define response headers for CSV download
$headers = [
"Content-type" => "text/csv",
// Specifies the content type as CSV
"Content-Disposition" => "attachment; filename=products.csv",
// Instructs the browser to treat it as a downloadable attachment with the filename 'products.csv'
"Pragma" => "no-cache",
// Prevents caching by the browser
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
// Further cache control to ensure content revalidation
"Expires" => "0"
// Sets the expiration date of the content to indicate it's already expired
];
// Create a callback function for the response
$callback = function () {
// Open a writable stream to php://output (the browser)
$file = fopen('php://output', 'w');
// Write the header row to the CSV
fputcsv($file, ['SKU', 'Name', 'Description', 'Price']);
// Query the products in chunks of 100 records
Product::chunk(100, function ($products) use ($file) {
foreach ($products as $product) {
// Write each product's data to the CSV
fputcsv($file, [$product→sku, $product→name, $product->description, $product_price]);
}
});
// Close the CSV file
fclose($file);
};
// Create and return a response with the CSV data
// this is how you don't have to save file into your server..
return response()->stream($callback, 200, $headers);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment