PHP arrays are useful for storing information such as products, customers, orders, and reports. Sometimes you need to export this information so it can be opened in Microsoft Excel, Google Sheets, or another application.
One of the simplest ways to do this is by exporting your data to a CSV file.
In this guide, you'll learn how to export PHP arrays to CSV using fputcsv(), include column headers, and let visitors download the generated file.
What Is a CSV File?
CSV stands for Comma-Separated Values. It's a text-based format for storing tabular data.
Each line represents a row, and a delimiter, usually a comma, separates the columns.
For example:
ID,Name,Price
101,Keyboard,49.99
102,Mouse,24.50
103,Monitor,199.00
CSV files are commonly used for exporting reports, transferring information between applications, and working with spreadsheets.
Understanding fputcsv()
PHP provides the built-in fputcsv() function to write an array as a CSV row.
Its basic syntax is:
fputcsv($handle, $fields, ",", '"', "");
The arguments are:
$handle— an open writable file or stream.$fields— an array containing the values to export.","— the field delimiter.'"'— the character used to enclose fields when necessary.""— disables PHP's proprietary escape mechanism, allowing standard CSV quote escaping.
Specifying the escape argument explicitly is recommended for compatibility with modern PHP versions.
Unlike manually joining values with commas, fputcsv() handles fields containing commas, quotation marks, and other special characters.
Exporting a Simple PHP Array
Let's start by writing a single row to a CSV file.
<?php
$file = fopen(__DIR__ . "/example.csv", "w");
if ($file === false) {
exit("Unable to create the CSV file.");
}
fputcsv(
$file,
["101", "Keyboard", "49.99"],
",",
'"',
""
);
fclose($file);
echo "CSV file created.";
PHP creates example.csv in the same directory as the script.
The "w" mode opens the file for writing and replaces its existing contents. If the file doesn't exist, PHP attempts to create it.
fclose() closes the file when writing is finished.
Exporting Associative Arrays with Headers
Real applications commonly store records as associative arrays.
For example:
$product = [
"id" => 101,
"name" => "Keyboard",
"price" => "49.99"
];
When exporting multiple records, it's important to keep the columns in a consistent order.
You should also include a header row so spreadsheet applications can identify each column.
Practical Example: Exporting a Product List
Let's build a complete script that exports product information into a CSV file.
Create a file named export-products.php:
<?php
declare(strict_types=1);
// Product data.
$products = [
[
"id" => 101,
"name" => "Keyboard",
"price" => "49.99"
],
[
"id" => 102,
"name" => "Wireless Mouse",
"price" => "24.50"
],
[
"id" => 103,
"name" => "27-inch Monitor",
"price" => "199.00"
]
];
// Open the destination file.
$filePath = __DIR__ . "/products.csv";
$handle = fopen($filePath, "w");
if ($handle === false) {
exit("Unable to create the CSV file.");
}
try {
// Write column headers.
if (
fputcsv(
$handle,
["ID", "Name", "Price"],
",",
'"',
""
) === false
) {
throw new RuntimeException("Unable to write headers.");
}
// Write product records.
foreach ($products as $product) {
$row = [
$product["id"],
$product["name"],
$product["price"]
];
if (fputcsv($handle, $row, ",", '"', "") === false) {
throw new RuntimeException("Unable to write a row.");
}
}
echo "Products exported successfully.";
} finally {
fclose($handle);
}
Run the script:
php export-products.php
The script creates a file named products.csv.
Generated CSV contents:
ID,Name,Price
101,Keyboard,49.99
102,"Wireless Mouse",24.50
103,"27-inch Monitor",199.00
Depending on the values, PHP may add quotation marks around fields. This is normal CSV formatting.
The example explicitly selects the columns instead of relying on the order of associative array keys.
It also checks for write failures and uses finally to close the file handle.
Allowing Visitors to Download a CSV File
Instead of saving a CSV file on the server, you can generate it directly as a browser download.
PHP provides the php://output stream for writing data to the HTTP response.
Create a separate file named download-csv.php:
<?php
declare(strict_types=1);
$products = [
[101, "Keyboard", "49.99"],
[102, "Mouse", "24.50"]
];
// Send download headers before any output.
header("Content-Type: text/csv; charset=UTF-8");
header('Content-Disposition: attachment; filename="products.csv"');
$output = fopen("php://output", "w");
if ($output === false) {
exit;
}
// Write the CSV data.
fputcsv($output, ["ID", "Name", "Price"], ",", '"', "");
foreach ($products as $product) {
fputcsv($output, $product, ",", '"', "");
}
fclose($output);
exit;
Open the script through a PHP-enabled web server. The browser will receive a CSV download named products.csv.
This approach is useful for downloadable reports and administrative exports.
In production, handle write errors appropriately and ensure download endpoints enforce any required authentication and authorization.
CSV Encoding and Excel Compatibility
When exporting text containing international characters, use UTF-8 encoding.
Some spreadsheet applications may need a UTF-8 Byte Order Mark (BOM) to recognize the encoding correctly.
If your target application requires one, write it before the first CSV row:
fwrite($output, "/xEF/xBB/xBF");
The BOM is optional. Not every CSV consumer expects it, so include it only when needed.
Security note: When CSV data comes from users or other untrusted sources, values beginning with spreadsheet formula characters such as =, +, -, or @ may be interpreted as formulas by spreadsheet software. Validate or neutralize these fields according to the target spreadsheet application's behavior before exporting them.
Common CSV Export Mistakes
| Problem | Solution |
|---|---|
| Incorrect columns | Build rows in a consistent, predefined order. |
| Broken values containing commas | Use fputcsv() instead of manually joining fields. |
| Existing CSV data disappears | Remember that fopen() with "w" overwrites the file. |
| Downloaded file contains HTML | Send headers before output and keep the download response free of webpage content. |
| Special characters display incorrectly | Use UTF-8 and check whether the target application requires a BOM. |
Key Takeaways
- Use
fputcsv()to export PHP arrays into CSV format. - Use
fopen()andfclose()to manage CSV files. - Include column headers when exporting structured records.
- Keep CSV columns in a consistent order.
- Use
php://outputto generate downloadable CSV files. - Consider character encoding and spreadsheet formula injection when exporting user-provided data.
Exporting arrays to CSV is a straightforward way to share PHP application data with spreadsheets and external systems. By using fputcsv(), you can generate correctly formatted files without manually managing commas, quotation marks, or line breaks.