Sometimes, we want to extract data from a csv file in PHP.
In this article, we’ll look at how to extract data from a csv file in PHP.
How to extract data from a CSV file in PHP?
To extract data from a csv file in PHP, we can use the SplFileObject
class.
For instance, we write
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl(",", '"', "\\");
foreach ($file as $row) {
list($fruit, $quantity) = $row;
// ...
}
to create a SplFileObject
object with the csv file path string.
Then we write $file->setFlags(SplFileObject::READ_CSV);
to start reading the csv.
We call setCsvControl
to set the csv separator characters.
Then we use a foreach loop to read the value of each $row
.
Conclusion
To extract data from a csv file in PHP, we can use the SplFileObject
class.