PHP Handle CSV: Read, Write, and Process CSV Files Efficiently

PHP Handle CSV: Read, Write, and Process CSV Files Efficiently

Introduction

CSV (Comma-Separated Values) files are widely used for storing structured data, importing/exporting databases, and processing large datasets. PHP provides built-in functions to read, write, modify, and process CSV files efficiently.

This guide will cover:

Reading CSV files in PHP
Writing and modifying CSV files
Handling large CSV files efficiently
Importing CSV data into databases
Best practices for working with CSV files

By the end of this guide, you’ll be able to handle CSV files dynamically in your PHP applications.

1. Understanding CSV Format in PHP

CSV files store data in a plain-text format, where values are separated by commas or other delimiters (;, |, etc.).

Example CSV File (data.csv)

id,name,email
1,John Doe,john@example.com
2,Alice Smith,alice@example.com
3,Mark Johnson,mark@example.com

Each line represents a record, and each column is separated by a delimiter (, in this case).

PHP provides the fgetcsv() and fputcsv() functions for handling CSV files easily.

2. Reading CSV Files in PHP

Use fgetcsv() to read CSV files line by line.

Example: Reading a CSV File

$file = fopen("data.csv", "r");

while (($data = fgetcsv($file, 1000, ",")) !== false) {
    print_r($data);
}

fclose($file);

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 )  
Array ( [0] => 3 [1] => Mark Johnson [2] => mark@example.com )  

fgetcsv() reads each row as an array, making it easy to process data dynamically.

Always close the file using fclose() after reading to free resources.

3. Writing Data to a CSV File in PHP

Use fputcsv() to write data to a CSV file.

Example: Writing Data to a CSV File

$data = [
    ["id", "name", "email"],
    [1, "John Doe", "john@example.com"],
    [2, "Alice Smith", "alice@example.com"],
    [3, "Mark Johnson", "mark@example.com"]
];

$file = fopen("output.csv", "w");

foreach ($data as $row) {
    fputcsv($file, $row);
}

fclose($file);

echo "CSV file created successfully!";

Output (output.csv):

id,name,email
1,John Doe,john@example.com
2,Alice Smith,alice@example.com
3,Mark Johnson,mark@example.com

Use fputcsv() to format and write arrays directly into CSV files.

Ensure the file is closed with fclose() after writing.

4. Appending Data to an Existing CSV File

To append data without overwriting, use a (append mode) instead of w.

Example: Appending Data to CSV File

$file = fopen("output.csv", "a");

$newData = [4, "Emma Watson", "emma@example.com"];

fputcsv($file, $newData);

fclose($file);

echo "Data appended successfully!";

This method ensures that new records are added without deleting existing data.

5. Handling Large CSV Files Efficiently

For large CSV files, reading all data at once may cause memory exhaustion. Instead, use streaming (line-by-line reading).

Example: Efficiently Processing Large CSV Files

$file = fopen("large_data.csv", "r");

while (($data = fgetcsv($file, 10000, ",")) !== false) {
    // Process each row (e.g., insert into database)
}

fclose($file);

Streaming reduces memory usage by processing one row at a time.

Set a higher byte limit (e.g., 10000) to optimize reading.

6. Importing CSV Data into a MySQL Database

To store CSV data in a MySQL database, use fgetcsv() and insert data dynamically.

Example: Importing CSV Data into MySQL

$conn = new mysqli("localhost", "root", "", "test_db");

$file = fopen("data.csv", "r");
fgetcsv($file); // Skip header row

while (($row = fgetcsv($file, 1000, ",")) !== false) {
    $sql = "INSERT INTO users (id, name, email) VALUES ('$row[0]', '$row[1]', '$row[2]')";
    $conn->query($sql);
}

fclose($file);
$conn->close();

echo "CSV data imported successfully!";

Always skip the header row before inserting data.

Use parameterized queries (prepare()) for better security against SQL injection.

7. Converting CSV Data to JSON Format

Convert CSV data into JSON for API responses or modern web applications.

Example: Converting CSV to JSON

$file = fopen("data.csv", "r");
$csvData = [];

$headers = fgetcsv($file);

while (($row = fgetcsv($file, 1000, ",")) !== false) {
    $csvData[] = array_combine($headers, $row);
}

fclose($file);

$jsonData = json_encode($csvData, JSON_PRETTY_PRINT);

file_put_contents("output.json", $jsonData);

echo "CSV converted to JSON successfully!";

Output (output.json):

[
    {
        "id": "1",
        "name": "John Doe",
        "email": "john@example.com"
    },
    {
        "id": "2",
        "name": "Alice Smith",
        "email": "alice@example.com"
    },
    {
        "id": "3",
        "name": "Mark Johnson",
        "email": "mark@example.com"
    }
]

array_combine($headers, $row) maps headers to values for structured JSON output.

Use JSON_PRETTY_PRINT for better JSON readability.

Best Practices for Handling CSV in PHP

Use fgetcsv() for safe and efficient CSV parsing.
Use fputcsv() to write CSV files correctly formatted.
Always close files using fclose() to free system resources.
Use streaming techniques for handling large CSV files.
Use parameterized queries when importing CSV into databases.

Conclusion

Handling CSV files in PHP is essential for data processing, exporting reports, and API integrations. By mastering reading, writing, appending, and importing CSV files, you can efficiently manage structured data in web applications.

By following best practices and optimizing performance, your PHP application can handle CSV files effectively and securely. 🚀

Leave a Reply