Importing a CSV file with the SplFileObject PHP class
Published on 2024-07-06 • Modified on 2024-07-06
This snippet shows how to import a CSV file with the SplFileObject PHP class. What is excellent about this class is that it will automatically detect separators. Here is a sample of the CSV file:
1,Dupont,Jean,jean.dupont@example.com,25,Paris
<?php
declare(strict_types=1);
namespace App\Controller\Snippet;
/**
* I am using a PHP trait to isolate each snippet in a file.
* This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
* or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
* Services are injected in the main controller constructor.
*/
trait Snippet308Trait
{
public function snippet308(): void
{
$csvFile = \dirname(__DIR__, 3).'/data/data.csv';
$file = new \SplFileObject($csvFile);
$file->setFlags(\SplFileObject::READ_CSV);
foreach ($file as $fields) {
/** @var array<string, string> $fields */
if (\count(array_filter($fields)) > 0) { // ignore last empty line
var_dump($fields);
}
}
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Read the doc More on the web Random snippet