Learn how to parse and format CSV strings in PHP using fgetcsv()
, str_getcsv()
, and fputcsv()
. Process CSV data efficiently for storage and APIs.
Introduction
CSV (Comma-Separated Values) is a widely used format for storing, exchanging, and processing structured data. Whether working with database exports, API responses, or spreadsheet data, PHP provides built-in functions to handle CSV files and strings efficiently.
This guide covers:
- Reading CSV data from files
- Parsing CSV strings into arrays
- Writing and formatting CSV data
- Best practices for handling CSV files securely
1. Reading CSV Files in PHP Using fgetcsv()
The fgetcsv()
function reads CSV data line by line from a file and converts it into an array.
Example: Reading a CSV File
$file = fopen("data.csv", "r");
while (($row = fgetcsv($file)) !== false) {
print_r($row);
}
fclose($file);
fopen("data.csv", "r")
opens the CSV file in read mode.fgetcsv()
reads one row at a time and converts it into an array.- The loop processes each line until reaching the end of the file.
Example CSV File (data.csv
)
id,name,email
1,John Doe,john@example.com
2,Alice Smith,alice@example.com
Output
Array ( [0] => id [1] => name [2] => email )
Array ( [0] => 1 [1] => John Doe [2] => john@example.com )
Array ( [0] => 2 [1] => Alice Smith [2] => alice@example.com )
2. Parsing CSV Strings with str_getcsv()
The str_getcsv()
function converts a CSV-formatted string into an array without needing a file.
Example: Parsing a CSV String
$csvString = "1,John Doe,john@example.com";
$data = str_getcsv($csvString);
print_r($data);
Output
Array ( [0] => 1 [1] => John Doe [2] => john@example.com )
- Useful for processing CSV data received from APIs or user input.
3. Writing Data to a CSV File Using fputcsv()
The fputcsv()
function writes an array as a CSV row into a file.
Example: Writing Data to a CSV File
$file = fopen("output.csv", "w");
$data = [
["id", "name", "email"],
[1, "John Doe", "john@example.com"],
[2, "Alice Smith", "alice@example.com"]
];
foreach ($data as $row) {
fputcsv($file, $row);
}
fclose($file);
Output File (output.csv
)
id,name,email
1,John Doe,john@example.com
2,Alice Smith,alice@example.com
- The foreach loop writes multiple rows to the CSV file.
fputcsv()
automatically handles escaping special characters like commas and quotes.
4. Handling CSV Data with Custom Delimiters
CSV files can use different delimiters, such as ;
or |
, instead of commas.
Example: Parsing CSV with a Semicolon (;
)
$file = fopen("semicolon_data.csv", "r");
while (($row = fgetcsv($file, 1000, ";")) !== false) {
print_r($row);
}
fclose($file);
- The third argument in
fgetcsv($file, 1000, ";")
specifies a custom delimiter.
Example: Writing CSV Data with a Pipe (|
)
$file = fopen("pipe_output.csv", "w");
$data = [
["id", "name", "email"],
[1, "John Doe", "john@example.com"],
[2, "Alice Smith", "alice@example.com"]
];
foreach ($data as $row) {
fputcsv($file, $row, "|");
}
fclose($file);
Output File (pipe_output.csv
)
id|name|email
1|John Doe|john@example.com
2|Alice Smith|alice@example.com
- The third parameter in
fputcsv()
sets the delimiter to|
.
5. Handling CSV Data Securely
1. Validate and Sanitize Input
Before processing CSV data, ensure it does not contain malicious content.
$handle = fopen("data.csv", "r");
while (($row = fgetcsv($handle)) !== false) {
$sanitized = array_map("htmlspecialchars", $row);
print_r($sanitized);
}
fclose($handle);
htmlspecialchars()
prevents cross-site scripting (XSS) attacks.
2. Handle Large CSV Files Efficiently
When processing large CSV files, avoid loading everything into memory.
$file = fopen("large.csv", "r");
while (($row = fgetcsv($file, 1000)) !== false) {
// Process each row individually
}
fclose($file);
- Reads the file line by line, preventing memory overload.
3. Prevent CSV Injection Attacks
CSV injection occurs when a malicious user inputs formulas that execute when the file is opened in a spreadsheet.
Example: Malicious CSV Content
=SUM(A1:A10)
@cmd /C calc.exe
To prevent this, prefix fields with a single quote ('
):
function sanitize_csv($data) {
return preg_replace('/^[@=+\\-]/', "'$0", $data);
}
$file = fopen("safe_output.csv", "w");
$data = [
["name", "balance"],
["Alice", "=SUM(A1:A10)"],
["Bob", "+100"]
];
foreach ($data as $row) {
$sanitizedRow = array_map("sanitize_csv", $row);
fputcsv($file, $sanitizedRow);
}
fclose($file);
- Protects against malicious spreadsheet formulas.
6. Best Practices for Handling CSV in PHP
✅ Use fgetcsv()
to read CSV files safely.
✅ Use str_getcsv()
for parsing CSV strings received from APIs.
✅ Use fputcsv()
instead of manual string concatenation for writing data.
✅ Specify custom delimiters when needed (e.g., ;
or |
).
✅ Sanitize input to prevent XSS and CSV injection attacks.
✅ Process large files line-by-line to avoid memory issues.
Conclusion
Handling CSV data in PHP is essential for data exchange, API integration, and file management. Understanding how to read, write, and process CSV data securely improves the reliability and efficiency of applications.
This guide covered:
- Reading CSV files with
fgetcsv()
- Parsing CSV strings with
str_getcsv()
- Writing CSV files using
fputcsv()
- Handling large CSV files and securing data
By following best practices, you can safely and efficiently process CSV data in PHP applications.