Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
<?php // Reading a CSV file $csvPath = '/var/data/users.csv'; $handle = fopen($csvPath, 'r'); if ($handle === false) { throw new RuntimeException("Cannot open $csvPath"); } $headers = fgetcsv($handle); // First row = headers $users = []; while (($row = fgetcsv($handle)) !== false) { if (count($row) !== count($headers)) continue; // skip malformed $users[] = array_combine($headers, $row); } fclose($handle); foreach ($users as $user) { printf("Name: %s, Email: %s ", $user['name'], $user['email']); } // Writing a CSV file $outputPath = '/var/data/export.csv'; $handle = fopen($outputPath, 'w'); // UTF-8 BOM for Excel compatibility fwrite($handle, "\xEF\xBB\xBF"); // Write header row fputcsv($handle, ['ID', 'Name', 'Email', 'Registered']); // Write data rows $data = [ [1, 'Alice Smith', 'alice@example.com', '2024-01-15'], [2, 'Bob O'Brien', 'bob@example.com', '2024-02-20'], [3, 'Carol Davis', 'carol@example.com', '2024-03-05'], ]; foreach ($data as $row) { fputcsv($handle, $row); } fclose($handle); // Parse a CSV string $line = 'John,"Doe, Jr.",john@example.com'; $cols = str_getcsv($line); print_r($cols); // ['John', 'Doe, Jr.', 'john@example.com']
Result
Open