Current Location: Home> Latest Articles> Practical Methods and Examples for Efficient CSV File Handling with PHP

Practical Methods and Examples for Efficient CSV File Handling with PHP

M66 2025-07-10

Basic Methods for Handling CSV Data with PHP Functions

CSV (Comma-Separated Values) is a widely used structured text data format. PHP provides multiple built-in functions to easily read, write, and manipulate CSV files, significantly simplifying development tasks.

Reading CSV Files

$handle = fopen('data.csv', 'r');
while (($row = fgetcsv($handle)) !== FALSE) {
    // Process each row of data
}
fclose($handle);

Writing to CSV Files

$handle = fopen('data.csv', 'w');
fputcsv($handle, ['col1', 'col2', 'col3']);
fclose($handle);

Parsing a CSV Line

$row = fgetcsv($handle);
$values = explode(',', $row[0]);

Joining Array Elements into a CSV Line

$row = ['col1', 'col2', 'col3'];
$csvLine = implode(',', $row);

Optimized Handling for Large CSV Files

To avoid memory overflow in constrained environments, using the generator-based SplFileObject class can efficiently handle large files:

$handle = fopen('data.csv', 'r');
$csv = new SplFileObject('data.csv');
$csv->setFlags(SplFileObject::READ_CSV);

foreach ($csv as $row) {
    // Process each row of data
}

Practical Example: Importing User Data from a CSV File

Assuming you have a CSV file containing username, email, and password, the following code demonstrates how to read and import the users:

// Open the CSV file
$handle = fopen('users.csv', 'r');

// Skip the header row
fgetcsv($handle);

// Read and process each user record
while (($row = fgetcsv($handle)) !== FALSE) {
    $username = $row[0];
    $email = $row[1];
    $password = $row[2];

    // Call your custom function to insert user
    insert_user($username, $email, $password);
}

fclose($handle);