0
0
PHPprogramming~10 mins

CSV file reading and writing in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - CSV file reading and writing
Open CSV file
Read line
Parse CSV line
Process data
Repeat until EOF
Close file
Open CSV file for writing
Write data line
Repeat for all lines
Close file
Open a CSV file, read each line parsing CSV data, process it, then close. For writing, open file, write lines, then close.
Execution Sample
PHP
<?php
$handle = fopen('data.csv', 'r');
while (($data = fgetcsv($handle)) !== false) {
    print_r($data);
}
fclose($handle);
?>
This code reads a CSV file line by line and prints each row as an array.
Execution Table
StepActionFunction CallData Read/WriteOutput/Result
1Open file for readingfopen('data.csv', 'r')File openedResource handle assigned
2Read first linefgetcsv(handle)"John,Doe,30"Array('John', 'Doe', '30') printed
3Read second linefgetcsv(handle)"Jane,Smith,25"Array('Jane', 'Smith', '25') printed
4Read third linefgetcsv(handle)"Bob,Brown,40"Array('Bob', 'Brown', '40') printed
5Read next linefgetcsv(handle)EOF reachedfalse returned, loop ends
6Close filefclose(handle)File closedNo output
7Open file for writingfopen('output.csv', 'w')File openedResource handle assigned
8Write first linefputcsv(handle, ['Name', 'Age'])Writes "Name,Age\n"1 (success) returned
9Write second linefputcsv(handle, ['Alice', '28'])Writes "Alice,28\n"1 (success) returned
10Close filefclose(handle)File closedNo output
💡 Reading stops when fgetcsv returns false at EOF; writing stops after all lines written and file closed.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6After Step 8After Step 9Final
handlenullresourceresourceresourceresourcenullresourceresourcenull
datanull['John', 'Doe', '30']['Jane', 'Smith', '25']['Bob', 'Brown', '40']falsefalsenullnullnull
Key Moments - 3 Insights
Why does the loop stop reading the CSV file?
The loop stops because fgetcsv returns false when it reaches the end of the file, as shown in step 5 of the execution_table.
What does fputcsv return after writing a line?
fputcsv returns 1 on success after writing a line, as seen in steps 8 and 9 of the execution_table.
Why do we need to close the file after reading or writing?
Closing the file releases system resources and ensures data is saved properly, shown in steps 6 and 10 where fclose is called.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'data' after step 3?
A['Jane', 'Smith', '25']
B['John', 'Doe', '30']
Cfalse
Dnull
💡 Hint
Check the 'data' column in the variable_tracker after step 3.
At which step does reading from the CSV file stop?
AStep 4
BStep 5
CStep 6
DStep 7
💡 Hint
Look at the execution_table where fgetcsv returns false indicating EOF.
If we forget to call fclose after writing, what might happen?
AData might not be saved properly
BFile will be deleted automatically
CReading will stop early
DNothing, fclose is optional
💡 Hint
Refer to key_moments about why closing files is important.
Concept Snapshot
CSV file reading and writing in PHP:
- Use fopen() to open file ('r' for read, 'w' for write)
- Use fgetcsv() to read CSV lines as arrays
- Use fputcsv() to write arrays as CSV lines
- Loop reading until fgetcsv returns false (EOF)
- Always fclose() to close the file and save resources
Full Transcript
This visual execution trace shows how to read and write CSV files in PHP. First, fopen opens the file for reading. Then, a while loop uses fgetcsv to read each line as an array until it returns false at the end of the file. Each array is printed. After reading, fclose closes the file. For writing, fopen opens the file in write mode. fputcsv writes arrays as CSV lines. After writing all lines, fclose closes the file. Variables like 'handle' track the file resource, and 'data' holds the current CSV row. Closing files is important to save data and free resources.