Last active
May 16, 2023 03:02
-
-
Save mehul0810/f49b2c318836c7a9d81fb8fa1580dbd6 to your computer and use it in GitHub Desktop.
Easily Export Data to CSV with PHP: A Comprehensive Guide for Beginners & Developers https://mehulgohil.com/blog/export-data-to-csv-using-php/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* CSV Export functionality using PHP. | |
* | |
* For development enquiries head over to https://mehulgohil.com/contact/ | |
* | |
* @author Mehul Gohil | |
*/ | |
// Start the output buffer. | |
ob_start(); | |
// Set PHP headers for CSV output. | |
header('Content-Type: text/csv; charset=utf-8'); | |
header('Content-Disposition: attachment; filename=csv_export.csv'); | |
// Create the headers. | |
$header_args = array( 'ID', 'Name', 'Email' ); | |
// Prepare the content to write it to CSV file. | |
$data = array( | |
array('1', 'Test 1', '[email protected]'), | |
array('2', 'Test 2', '[email protected]'), | |
array('3', 'Test 3', '[email protected]'), | |
); | |
// Clean up output buffer before writing anything to CSV file. | |
ob_end_clean(); | |
// Create a file pointer with PHP. | |
$output = fopen( 'php://output', 'w' ); | |
// Write headers to CSV file. | |
fputcsv( $output, $header_args ); | |
// Loop through the prepared data to output it to CSV file. | |
foreach( $data as $data_item ){ | |
fputcsv( $output, $data_item ); | |
} | |
// Close the file pointer with PHP with the updated output. | |
fclose( $output ); | |
exit; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment