0
0
PHPprogramming~5 mins

CSV file reading and writing in PHP

Choose your learning style9 modes available
Introduction

CSV files are simple text files that store data in a table form. Reading and writing CSV files lets your PHP programs save and load data easily.

You want to save user data like names and emails in a simple file.
You need to read data exported from spreadsheet programs like Excel.
You want to share data between different programs using a common format.
You want to log information in a readable and organized way.
You want to import or export data from a database in a simple format.
Syntax
PHP
<?php
// Reading CSV file
if (($handle = fopen('file.csv', 'r')) !== false) {
    while (($data = fgetcsv($handle, 1000, ',')) !== false) {
        // $data is an array of values from one line
    }
    fclose($handle);
}

// Writing CSV file
if (($handle = fopen('file.csv', 'w')) !== false) {
    fputcsv($handle, ['value1', 'value2', 'value3']);
    fclose($handle);
}

fgetcsv() reads one line from the file and splits it into an array by commas.

fputcsv() writes an array as a comma-separated line to the file.

Examples
This reads each line from data.csv and prints the array of values.
PHP
<?php
// Read CSV and print each row
if (($handle = fopen('data.csv', 'r')) !== false) {
    while (($row = fgetcsv($handle)) !== false) {
        print_r($row);
    }
    fclose($handle);
}
This writes a header row and one data row to output.csv.
PHP
<?php
// Write two rows to CSV
if (($handle = fopen('output.csv', 'w')) !== false) {
    fputcsv($handle, ['Name', 'Age', 'City']);
    fputcsv($handle, ['Alice', '30', 'Paris']);
    fclose($handle);
}
Sample Program

This program writes a small table of people to people.csv and then reads it back, printing each row with values separated by |.

PHP
<?php
// Create and write to CSV
$file = 'people.csv';
$data = [
    ['Name', 'Age', 'City'],
    ['John', '25', 'New York'],
    ['Anna', '28', 'London'],
    ['Mike', '32', 'Sydney']
];

$handle = fopen($file, 'w');
foreach ($data as $row) {
    fputcsv($handle, $row);
}
fclose($handle);

// Read and print CSV
if (($handle = fopen($file, 'r')) !== false) {
    while (($row = fgetcsv($handle)) !== false) {
        echo implode(' | ', $row) . "\n";
    }
    fclose($handle);
}
OutputSuccess
Important Notes

Always close the file with fclose() to save changes and free resources.

Use the correct file path and permissions to avoid errors when opening files.

CSV files separate values by commas by default, but you can change the delimiter in fgetcsv and fputcsv if needed.

Summary

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

Use fputcsv() to write arrays as CSV lines to files.

Always open files with fopen() and close them with fclose().