Web Analytics

PHP CSV Files

Intermediate~25 min read

CSV (Comma-Separated Values) files are perfect for data import/export. Learn to read and write CSV files with PHP's built-in functions!

Output
Click Run to execute your code

Write CSV

<?php
$data = [
    ['Name', 'Email', 'Age'],
    ['John', '[email protected]', 30],
    ['Jane', '[email protected]', 25]
];

$handle = fopen('users.csv', 'w');
foreach ($data as $row) {
    fputcsv($handle, $row);
}
fclose($handle);
?>

Read CSV

<?php
$handle = fopen('users.csv', 'r');
while (($row = fgetcsv($handle)) !== false) {
    print_r($row);
}
fclose($handle);
?>

Summary

  • fputcsv(): Write CSV row
  • fgetcsv(): Read CSV row
  • Headers: First row as column names
  • Use case: Data import/export

What's Next?

Next, learn about JSON Files - working with JavaScript Object Notation!