How to handle CSV file with PHP
The function that parses the CSV file is fgetcsv, with the following syntax:
fgetcsv("filename.csv", 1000, ",");
- The name of the CSV file
- 1000 - The length of the longest line
- "," - Optional delimiter parameter. The default is, of course, comma
In order to use the fgetcsv function, we need to first open the file for reading with fopen, and end the code by closing the file with fclose. In between, we use a loop inside of which we parse each CSV row separately.
Let's write the code.
The first step is opening the file for reading with fopen:
$h = fopen("filename.csv", "r");
We use the "r" mode in order to open the file for reading.
The $h variable is the handle that holds the data from the file.
The second step is reading the file line-by-line using fgetcsv, and converting each row individually into an array that we call $data.
$data = fgetcsv($h, 1000, ",");
fgetcsv includes the handle ($h), from the previous section, and in order to read all the lines, we'll run in it inside a while loop.
while (($data = fgetcsv($h, 1000, ",")) !== FALSE)
{
// Read the data
}
Lastly, we need to close the file.
fclose($h);
Let's combine the 3 steps:
<?php
// Open the file for reading
if (($h = fopen("cars.csv", "r")) !== FALSE)
{
// Convert each line into the local $data variable
while (($data = fgetcsv($h, 1000, ",")) !== FALSE)
{
// Read the data from a single line
}
// Close the file
fclose($h);
}