Tags: PHP
Class to open a csv file, set headers from the first row, then iterate through each row:
class CSVreader
{
// resource of the opened file
protected $file;
// headers of the CSV (first row)
protected $headers = [];
public function __construct()
{
// Read file
$filePath = '/file.csv';
$this->file = fopen($filePath, 'r');
// Set headers from CSV
$this->getHeaders(fgetcsv($this->file));
}
/**
* Main public function to iterate through the csv rows.
*
* @return mixed
*/
public function iterate()
{
// iterate through file, open each line as csv
while ($row = fgetcsv($this->file)) {
// Example of printing an element from the "Column name" column
var_dump($this->getRowElement($row, "Column name"));
// do anything else you want with the row
}
}
/**
* Fill in headers from the first row.
*
* @return void
*/
private function getHeaders($row)
{
if (count($this->headers) == 0) {
foreach ($row as $i => $name) {
$this->headers[$name] = $i;
}
}
}
/**
* Get row element by the name of the column (header).
*
* @return mixed
*/
private function getRowElement($row, $col)
{
return $row[$this->headers[$col]];
}
}
©2023, kirillsimin.com