Skip to content
PHP Logo

What is the recommended method for reading CSV files in PHP?

When reading CSV files in PHP, the recommended method is to use the built-in function `fgetcsv()` which reads a line from an open file pointer and parses it as CSV fields. This function handles CSV parsing including handling of commas, quotes, and line breaks within fields.

php
$filename = 'example.csv';
$handle = fopen($filename, 'r');

if ($handle !== false) {
    while (($data = fgetcsv($handle)) !== false) {
        // Process the CSV data here
        print_r($data);
    }
    fclose($handle);
} else {
    echo 'Error opening file';
}