0
0
PHPprogramming~30 mins

CSV file reading and writing in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
CSV file reading and writing
📖 Scenario: You work in a small shop and want to keep track of your products and prices using a CSV file. You will read the CSV file, update prices, and save the changes back to the file.
🎯 Goal: Build a PHP script that reads a CSV file named products.csv, updates the prices by increasing them by 10%, and writes the updated data back to the same CSV file.
📋 What You'll Learn
Read data from a CSV file named products.csv
Store the CSV data in an array
Increase each product's price by 10%
Write the updated data back to products.csv
Use PHP built-in functions for CSV handling
💡 Why This Matters
🌍 Real World
Small shops or simple apps often use CSV files to store product lists and prices because CSV files are easy to read and edit.
💼 Career
Knowing how to read and write CSV files is useful for data import/export tasks, report generation, and simple database alternatives in PHP development.
Progress0 / 4 steps
1
Create the initial CSV file
Create a CSV file named products.csv with these exact lines:
Apple,1.00
Banana,0.50
Cherry,2.00
PHP
Need a hint?

Use file_put_contents to create and write to the CSV file.

2
Read the CSV file into an array
Read the CSV file products.csv line by line using fopen and fgetcsv, and store each row as an array inside a variable called products.
PHP
Need a hint?

Use fopen to open the file and fgetcsv inside a while loop to read each row.

3
Increase each product price by 10%
Use a foreach loop with variables index and product to iterate over products. Increase the price (second element) by 10% and update products[index][1] with the new price formatted to 2 decimal places.
PHP
Need a hint?

Convert the price to float, multiply by 1.10, then format back to string with 2 decimals.

4
Write the updated data back to the CSV file
Open products.csv for writing using fopen with mode 'w'. Use a foreach loop to write each product array to the file using fputcsv. Close the file with fclose. Then print "Updated CSV saved." to confirm.
PHP
Need a hint?

Use fopen with 'w' mode, fputcsv inside a loop, then fclose. Finally, print the confirmation message.