Skip to content

Instantly share code, notes, and snippets.

@MrPunyapal
Last active December 31, 2023 07:29
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MrPunyapal/15825d49731d6f5170a15a8389c0b789 to your computer and use it in GitHub Desktop.
Save MrPunyapal/15825d49731d6f5170a15a8389c0b789 to your computer and use it in GitHub Desktop.
PHP Function to Export Products as CSV (without saving it in server)
<?php
function exportCSV()
{
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=products.csv');
header('Pragma: no-cache');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$file = fopen('php://output', 'w');
fputcsv($file, ['SKU', 'Name', 'Description', 'Price']);
// Simulate fetching data from a database (replace with your data source)
$products = [
['12345', 'Product 1', 'Description 1', 19.99],
['67890', 'Product 2', 'Description 2', 29.99],
];
foreach ($products as $product) {
fputcsv($file, $product);
}
fclose($file);
}
<?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