0
0
PHPprogramming~10 mins

CSV file reading and writing in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to open a CSV file for reading.

PHP
<?php
$handle = fopen('data.csv', '[1]');
?>
Drag options to blanks, or click blank then click option'
A'a'
B'w'
C'r'
D'x'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' or 'a' mode which are for writing or appending.
Forgetting to put the mode in quotes.
2fill in blank
medium

Complete the code to read a line from the CSV file as an array.

PHP
<?php
$handle = fopen('data.csv', 'r');
$row = fgetcsv([1]);
?>
Drag options to blanks, or click blank then click option'
A$file
B$handle
C$csv
D$data
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable that was not assigned to fopen.
Passing a string filename instead of the file handle.
3fill in blank
hard

Fix the error in the code to write an array as a CSV line.

PHP
<?php
$handle = fopen('output.csv', 'w');
fputcsv([1], ['apple', 'banana', 'cherry']);
fclose($handle);
?>
Drag options to blanks, or click blank then click option'
A$csv
B$file
C$data
D$handle
Attempts:
3 left
💡 Hint
Common Mistakes
Passing an undefined variable to fputcsv.
Confusing the file handle variable name.
4fill in blank
hard

Fill both blanks to read all lines from a CSV file into an array.

PHP
<?php
$handle = fopen('data.csv', 'r');
$data = [];
while (($row = fgetcsv([1])) [2] false) {
    $data[] = $row;
}
fclose($handle);
?>
Drag options to blanks, or click blank then click option'
A$handle
B$file
C!==
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '!==' in the while condition.
Using wrong variable for the file handle.
5fill in blank
hard

Fill all three blanks to write multiple rows to a CSV file using a loop.

PHP
<?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);
?>
Drag options to blanks, or click blank then click option'
A$rows
B$row
C$handle
D$data
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names in the foreach loop.
Passing wrong variable to fputcsv.