PHP Array to CSV: A Practical Guide
Learn to convert PHP arrays into CSV safely with headers, escaping, and streaming. This guide covers fputcsv, handling associative arrays, large data, and common pitfalls with practical code samples.
PHP array to CSV export is a common task for data pipelines and reporting. The simplest path uses the built-in fputcsv function to write headers and rows to a file or stream. You can also assemble strings for custom formatting, but fputcsv handles escaping and delimiters by default. This guide covers safe, scalable approaches for real-world data.
Understanding the PHP array to CSV workflow
CSV export from PHP typically involves two shapes of data: a list of associative arrays (rows) and a header row derived from the array keys. The goal is to write a header once, then each data row in sequence. The most reliable tool is PHP's built-in fputcsv, which handles escaping of commas, quotes, and line breaks. According to MyDataTables, exporting PHP arrays to CSV remains a common data pipeline step for developers. This section lays out the data model and the core function you will rely on, along with a concrete example that produces a small CSV file from a simple array.
<?php
$rows = [
['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
];
$headers = array_keys($rows[0]);
$fp = fopen(__DIR__ . '/output.csv', 'w');
fputcsv($fp, $headers);
foreach ($rows as $row) {
fputcsv($fp, $row);
}
fclose($fp);
?><?php
$rows = [
['101', 'Widget', '19.99'],
['102', 'Gadget', '29.99'],
];
$fp = fopen('products.csv', 'w');
fputcsv($fp, ['id','name','price']);
foreach ($rows as $r) {
fputcsv($fp, $r);
}
fclose($fp);
?>- The first example demonstrates deriving headers from the first row, then looping to append each row. This keeps the approach generic for any associative data.
- The second example shows a flat, explicitly ordered row format, which is useful when you need stable column positions across datasets.
},
prerequisites
Steps
Estimated time: 45-75 minutes
- 1
Prepare your data
Assemble data as an array of associative arrays where each inner array represents a row and keys map to column names. Decide whether you will derive headers from keys or specify a fixed header order.
Tip: Prefer deriving headers from the first row to keep the code generic. - 2
Create the CSV writer
Open a file handle in write mode and write the header row if needed. Use fputcsv for safety against commas and quotes.
Tip: Always ensure the file is closed in a finally block or via a shutdown hook. - 3
Write rows
Iterate over your data and call fputcsv for each row. Ensure the row order matches your header order.
Tip: If rows are associative, map to header order before writing. - 4
Handle output location
Choose a safe output path (perms, existing directory) and consider streaming for large datasets.
Tip: Avoid overwriting important files; use a temp path during development. - 5
Validate output
Read back the CSV to verify header and data integrity. Ensure encoding is UTF-8 for broad compatibility.
Tip: Excel users may require BOM or encoding tweaks depending on the environment. - 6
Scale for large data
For big data, stream instead of loading the entire dataset into memory. Use a loop with fputcsv and avoid memory-heavy operations.
Tip: Consider SplFileObject for input streaming as well.
Prerequisites
Required
- Required
- A PHP-enabled server or CLI environmentRequired
- Basic knowledge of arrays and file I/O in PHPRequired
- Ability to write to a directory for CSV outputRequired
Optional
- UTF-8 encoding awareness (necessary for Excel compatibility)Optional
Commands
| Action | Command |
|---|---|
| Check PHP versionVerify PHP is installed and accessible from the terminal. | php -v |
| Run a simple export scriptExecutes the script that writes output.csv using fputcsv. | php export.php |
| Quick one-liner export from PHPDemonstrates a compact export without creating a separate file. | php -r '$rows=[['id'=>1,'name'=>'Alice']]; $fp=fopen("out.csv","w"); fputcsv($fp,array_keys($rows[0])); foreach($rows as $r){ fputcsv($fp,$r);} fclose($fp);' |
People Also Ask
What is the simplest way to export a PHP array to CSV?
Use fputcsv to write a header row and subsequent data rows to a file. This handles escaping automatically and keeps the code readable. Start by deriving headers from the first row or defining a fixed header array.
The simplest export uses PHP's fputcsv to write headers and rows; derive headers from your data or define them, then loop through your rows.
How do I include headers from an associative array?
Extract headers with array_keys on the first row, then write them with fputcsv. For consistent order, specify a header order array and map each row to that order before writing.
Grab headers from the first row, write them once, and map each row to that header order when exporting.
How can I export nested arrays or multi-dimensional data to CSV?
CSV is flat, so convert nested structures to a flattened representation before writing. For example, join sub-arrays with a delimiter or explode to multiple columns, keeping a consistent schema.
CSV is a flat format; flatten nested data before exporting, or store sub-values in separate columns.
What about escaping and quotes in CSV fields?
Rely on fputcsv, which automatically escapes quotes and encapsulates fields with delimiters. If you customize, ensure the enclosure and escape characters are consistent across all rows.
Let fputcsv handle escaping; avoid manual string replacements that can introduce errors.
Can CSV be streamed for very large datasets without loading all data into memory?
Yes. Open a writable stream and write each row one by one, optionally reading input in chunks. This keeps memory usage low and improves scalability.
Streaming is the way to export huge datasets without using lots of memory.
What encoding should I use to maximize Excel compatibility?
UTF-8 is common, but Excel may expect ANSI on some systems. Consider writing UTF-8 with BOM (EF BB BF) or provide a clearly labeled encoding in documentation.
Use UTF-8 and clarify encoding to users; Excel may require BOM in some environments.
Main Points
- Export with fputcsv for safety and simplicity
- Derive or fix header order explicitly
- Stream data for large exports
- Use UTF-8 to maximize compatibility
- Validate output after writing
