Consider the following PHP code that reads a CSV file and prints each row as a JSON string.
$file = fopen('data.csv', 'r');
while (($row = fgetcsv($file)) !== false) {
echo json_encode($row) . "\n";
}
fclose($file);Assuming data.csv contains these lines:
apple,banana,cherry 1,2,3 x,y,z
What will be the output?
$file = fopen('data.csv', 'r'); while (($row = fgetcsv($file)) !== false) { echo json_encode($row) . "\n"; } fclose($file);
Remember that fgetcsv returns an array of fields for each line.
The fgetcsv function reads each line and splits it by commas into an array. Then json_encode converts the array to a JSON string. So each line is printed as a JSON array of strings.
Given this PHP code that writes data to a CSV file:
$data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles']
];
$file = fopen('output.csv', 'w');
foreach ($data as $row) {
fputcsv($file, $row);
}
fclose($file);What will be the content of output.csv after running this code?
$data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles']
];
$file = fopen('output.csv', 'w');
foreach ($data as $row) {
fputcsv($file, $row);
}
fclose($file);fputcsv writes arrays as comma-separated lines by default.
The fputcsv function writes each array as a line with comma-separated values. So the file will have three lines with commas separating the fields.
Look at this PHP code snippet:
$file = fopen('data.csv', 'r');
while ($row = fgetcsv($file)) {
print_r($row);
}
fclose($file);Sometimes it raises a warning: Warning: fgetcsv() expects parameter 1 to be resource, bool given. Why?
$file = fopen('data.csv', 'r'); while ($row = fgetcsv($file)) { print_r($row); } fclose($file);
Check the return value of fopen before using it.
If fopen fails (e.g., file missing), it returns false. Passing false to fgetcsv causes the warning because it expects a file resource.
Which PHP code snippet correctly reads all rows from a CSV file data.csv into an array $rows?
Remember operator precedence and correct syntax for while loops.
Option B uses parentheses to ensure fgetcsv($file) is called and its result compared to false. Option B misses strict comparison and may add false as a row. Option B has wrong operator precedence, assigning boolean to $row. Option B is invalid syntax.
You want to write a CSV file data.csv where fields are separated by semicolons (;) instead of commas. Which code snippet correctly does this?
Check the third parameter of fputcsv for delimiter.
Option D uses fputcsv with the third argument set to ; to change the delimiter. Option D uses comma, so default delimiter. Option D uses default comma delimiter. Option D writes a string manually, which works but is not using fputcsv.