CSV files are simple text files that store data in a table form. Reading and writing CSV files lets your PHP programs save and load data easily.
CSV file reading and writing in PHP
<?php // Reading CSV file if (($handle = fopen('file.csv', 'r')) !== false) { while (($data = fgetcsv($handle, 1000, ',')) !== false) { // $data is an array of values from one line } fclose($handle); } // Writing CSV file if (($handle = fopen('file.csv', 'w')) !== false) { fputcsv($handle, ['value1', 'value2', 'value3']); fclose($handle); }
fgetcsv() reads one line from the file and splits it into an array by commas.
fputcsv() writes an array as a comma-separated line to the file.
data.csv and prints the array of values.<?php // Read CSV and print each row if (($handle = fopen('data.csv', 'r')) !== false) { while (($row = fgetcsv($handle)) !== false) { print_r($row); } fclose($handle); }
output.csv.<?php // Write two rows to CSV if (($handle = fopen('output.csv', 'w')) !== false) { fputcsv($handle, ['Name', 'Age', 'City']); fputcsv($handle, ['Alice', '30', 'Paris']); fclose($handle); }
This program writes a small table of people to people.csv and then reads it back, printing each row with values separated by |.
<?php // Create and write to CSV $file = 'people.csv'; $data = [ ['Name', 'Age', 'City'], ['John', '25', 'New York'], ['Anna', '28', 'London'], ['Mike', '32', 'Sydney'] ]; $handle = fopen($file, 'w'); foreach ($data as $row) { fputcsv($handle, $row); } fclose($handle); // Read and print CSV if (($handle = fopen($file, 'r')) !== false) { while (($row = fgetcsv($handle)) !== false) { echo implode(' | ', $row) . "\n"; } fclose($handle); }
Always close the file with fclose() to save changes and free resources.
Use the correct file path and permissions to avoid errors when opening files.
CSV files separate values by commas by default, but you can change the delimiter in fgetcsv and fputcsv if needed.
Use fgetcsv() to read CSV files line by line into arrays.
Use fputcsv() to write arrays as CSV lines to files.
Always open files with fopen() and close them with fclose().
Practice
Solution
Step 1: Understand CSV reading functions
PHP providesfgetcsv()to read a line from a CSV file and convert it into an array of values.Step 2: Differentiate from writing functions
fputcsv()writes arrays to CSV files, whilefread()andfwrite()handle raw file reading/writing without CSV parsing.Final Answer:
fgetcsv() -> Option AQuick Check:
Read CSV line as array = fgetcsv() [OK]
- Confusing fgetcsv() with fputcsv()
- Using fread() which reads raw data, not CSV parsed
- Trying to read CSV without parsing into arrays
Solution
Step 1: Understand fopen modes
Mode 'w' opens a file for writing and truncates it if it exists, perfect for writing CSV files.Step 2: Check other modes
'r' is read-only, 'rw' is invalid, 'x' creates a new file but fails if it exists.Final Answer:
$file = fopen('data.csv', 'w'); -> Option CQuick Check:
Open file for writing = 'w' mode [OK]
- Using 'r' mode when intending to write
- Using invalid mode 'rw'
- Using 'x' which fails if file exists
$file = fopen('data.csv', 'r');
$data = fgetcsv($file);
fclose($file);
print_r($data);Assuming the first line of
data.csv is:John,Doe,30Solution
Step 1: Understand fgetcsv() output
fgetcsv() reads one CSV line and returns an array splitting values by commas.Step 2: Analyze given CSV line
The line 'John,Doe,30' splits into array elements: 'John', 'Doe', and '30'.Final Answer:
Array ( [0] => John [1] => Doe [2] => 30 ) -> Option AQuick Check:
fgetcsv() splits CSV line into array [OK]
- Expecting a string instead of an array
- Assuming fgetcsv returns raw line string
- Not closing the file after reading
$file = fopen('output.csv', 'r');
fputcsv($file, ['Alice', 'Smith', 25]);
fclose($file);Solution
Step 1: Check fopen mode
The file is opened with 'r' (read) mode, which does not allow writing.Step 2: Understand fputcsv requirements
fputcsv() requires the file to be opened in write ('w') or append ('a') mode to write data.Final Answer:
File opened in read mode instead of write mode -> Option DQuick Check:
Open file in write mode before writing [OK]
- Opening file in 'r' mode when writing
- Forgetting to close the file
- Misunderstanding fputcsv() input
Solution
Step 1: Open input file for reading and output file for writing
Use 'r' mode for reading input and 'w' mode for writing output.Step 2: Read each CSV row with fgetcsv() from input and check third column
Usefgetcsv($in)to read rows, then check if$row[2] > 50.Step 3: Write qualifying rows to output with fputcsv()
If condition passes, write row to output file usingfputcsv($out, $row).Final Answer:
Code snippet B correctly reads, filters, and writes CSV rows -> Option BQuick Check:
Read with fgetcsv(), filter by column, write with fputcsv() [OK]
- Opening files with wrong modes
- Using fgets() instead of fgetcsv() for CSV reading
- Mixing input and output file handles
Ready to prove it?
Pass the test and this pattern moves unknown
