Simple PHP CSV Export
Below is a basic example that exports an array of data to a CSV file: // Array of data to export $data = array( array('Name', 'Age', 'Email'), array('John Doe', '25', 'john@example.com'), array('Jane Doe', '28', 'jane@example.com'), array('Sam Smith', '22', 'sam@example.com') ); // Open output stream $filename = "output.csv"; $fp = fopen($filename, 'w'); // Write each row to CSV foreach ($data as $row) { fputcsv($fp, $row); } // Close the file fclose($fp); echo "Data exported to CSV successfully!";
In this example:
The $data array contains the data to be exported.
fopen() is used to open the CSV file.
fputcsv() writes each row to the file.
After writing all the rows, fclose() is used to close the file.
Download CSV Directly in Browser
You may want to directly download the CSV file in the browser instead of saving it on the server. Here’s how you can do that: // Array of data to export $data = array( array('Name', 'Age', 'Email'), array('John Doe', '25', 'john@example.com'), array('Jane Doe', '28', 'jane@example.com'), array('Sam Smith', '22', 'sam@example.com') ); // Set headers to force download header('Content-Type: text/csv'); header('Content-Disposition: attachment;filename="output.csv"'); // Open output stream $fp = fopen('php://output', 'w'); // Write each row to CSV foreach ($data as $row) { fputcsv($fp, $row); } // Close the file fclose($fp);
In this code:
The headers Content-Type and Content-Disposition will tell the browser to download the file as “output.csv”.
php://output is used to write the file directly to the browser.
Export Data from Database to CSV
You can also export data from MySql database to CSV. A simple example is given below: // Database connection (update with your own credentials) $conn = new mysqli("localhost", "username", "password", "database"); // Query to fetch data $sql = "SELECT name, age, email FROM users"; $result = $conn->query($sql); // Set headers to force download header('Content-Type: text/csv'); header('Content-Disposition: attachment;filename="users.csv"'); // Open output stream $fp = fopen('php://output', 'w'); // Write the header row fputcsv($fp, array('Name', 'Age', 'Email')); // Write the data rows while ($row = $result->fetch_assoc()) { fputcsv($fp, $row); } // Close the file fclose($fp); $conn->close();
In this example:
The MySQL query retrieves data from the users table.
The results are written to the CSV file using fputcsv().
Summary
Use fputcsv() to easily export data to a CSV file.You can either save the file on the server or force it to download in the browser.
CSV export can be combined with data fetched from a database for dynamic reports.
This is how you can export data to CSV using PHP. It is a very simple and effective way to generate downloadable files for users.