arrow_back
Back

Reading and writing CSV files in PHP

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

Reading

Using str_getcsv() line by line:

$spreadsheet_file = fopen($spreadsheet_path, 'r');

while (($line = fgets($spreadsheet_file)) !== false) {
    $cells = str_getcsv($line);
    // ...
}

Using fgetcsv(), which reads and parses a line in one call:

$row = 1;
if (($handle = fopen("test.csv", "r")) !== false) {
    while (($data = fgetcsv($handle, 1000, ",")) !== false) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c = 0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}

Writing

Using fputcsv():

<?php

$list = [
    ['aaa', 'bbb', 'ccc', 'dddd'],
    ['123', '456', '789'],
    ['"aaa"', '"bbb"'],
];

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Working with PDF files in PHP: OCR and PDF-to-image

arrow_forward