Bird
0
0

Identify the error in this PHP code snippet for reading a CSV file:

medium📝 Debug Q6 of 15
PHP - File Handling
Identify the error in this PHP code snippet for reading a CSV file:
$file = fopen('file.csv', 'r');
while ($line = fgets($file)) {
  $data = fgetcsv($line);
  print_r($data);
}
fclose($file);
AUsing fgets() instead of fgetcsv() in the loop condition
BPassing a string to fgetcsv() instead of a file handle
CNot closing the file after reading
DUsing print_r() instead of echo
Step-by-Step Solution
Solution:
  1. Step 1: Analyze fgetcsv() parameter

    fgetcsv() expects a file handle, but $line is a string from fgets().
  2. Step 2: Identify correct usage

    Use fgetcsv($file) directly in the loop to read CSV lines.
  3. Final Answer:

    Passing a string to fgetcsv() instead of a file handle -> Option B
  4. Quick Check:

    fgetcsv() needs file handle, not string [OK]
Quick Trick: Pass file handle to fgetcsv(), not string lines [OK]
Common Mistakes:
  • Using fgets() then fgetcsv() on string
  • Forgetting fclose()
  • Confusing print_r() with echo

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes