Complete the code to open a CSV file for reading.
<?php $handle = fopen('data.csv', '[1]'); ?>
To read a CSV file, you open it in read mode using 'r'.
Complete the code to read a line from the CSV file as an array.
<?php $handle = fopen('data.csv', 'r'); $row = fgetcsv([1]); ?>
The variable holding the file pointer is $handle, which is passed to fgetcsv to read a line.
Fix the error in the code to write an array as a CSV line.
<?php $handle = fopen('output.csv', 'w'); fputcsv([1], ['apple', 'banana', 'cherry']); fclose($handle); ?>
fputcsv requires the file handle as the first argument, which is $handle here.
Fill both blanks to read all lines from a CSV file into an array.
<?php $handle = fopen('data.csv', 'r'); $data = []; while (($row = fgetcsv([1])) [2] false) { $data[] = $row; } fclose($handle); ?>
We use $handle as the file pointer and check that fgetcsv does not return false to continue reading lines.
Fill all three blanks to write multiple rows to a CSV file using a loop.
<?php
$rows = [
['John', 'Doe', 30],
['Jane', 'Smith', 25],
['Bob', 'Johnson', 40]
];
$handle = fopen('people.csv', 'w');
foreach ([1] as [2]) {
fputcsv([3], $row);
}
fclose($handle);
?>The foreach loops over $rows as $row, and fputcsv writes each $row to the file handle $handle.
