Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to read a CSV file

Short answer

Open the file and read the lines with fgetcsv():

<?php
 
$file = sys_get_temp_dir() . '/recipe.csv';
file_put_contents($file, "name,price\nTea,250\nCoffee,400\n");
 
$handle = fopen($file, 'r');
 
while (($row = fgetcsv($handle, null, ',', '"', '')) !== false) {
    echo implode(' | ', $row), "\n";
}
 
fclose($handle);

Output:

name | price
Tea | 250
Coffee | 400

Rows with field names

Take the first line as the headings and join it with the rest through array_combine():

<?php
 
$file = sys_get_temp_dir() . '/recipe.csv';
file_put_contents($file, "name,price\nTea,250\nCoffee,400\n");
 
$handle = fopen($file, 'r');
$header = fgetcsv($handle, null, ',', '"', '');
$rows = [];
 
while (($row = fgetcsv($handle, null, ',', '"', '')) !== false) {
    $rows[] = array_combine($header, $row);
}
 
fclose($handle);
 
echo $rows[1]['name'], ' ', $rows[1]['price'];

Output:

Coffee 400

Functions used in this recipe

  • fgetcsv — Reads a line of a CSV file and splits it into fields.
  • fputcsv — Writes an array to a file as a CSV line.
  • array_combine — Creates an array from two lists: keys and values.

Thanks for reading!

Donate to the site — we work hard for you.