Skip to content

Instantly share code, notes, and snippets.

@adrianalonso
Created January 22, 2016 12:10
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save adrianalonso/69733bf2527a2ef56b32 to your computer and use it in GitHub Desktop.
Save adrianalonso/69733bf2527a2ef56b32 to your computer and use it in GitHub Desktop.
Symfony Command Import CSV
<?php
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ImportCountriesCommand extends ContainerAwareCommand
{
// change these options about the file to read
private $csvParsingOptions = array(
'finder_in' => 'app/Resources/',
'finder_name' => 'countries.csv',
'ignoreFirstLine' => true
);
protected function execute(InputInterface $input, OutputInterface $output)
{
// use the parseCSV() function
$csv = $this->parseCSV();
}
/**
* Parse a csv file
*
* @return array
*/
private function parseCSV()
{
$ignoreFirstLine = $this->csvParsingOptions['ignoreFirstLine'];
$finder = new Finder();
$finder->files()
->in($this->csvParsingOptions['finder_in'])
->name($this->csvParsingOptions['finder_name'])
;
foreach ($finder as $file) { $csv = $file; }
$rows = array();
if (($handle = fopen($csv->getRealPath(), "r")) !== FALSE) {
$i = 0;
while (($data = fgetcsv($handle, null, ";")) !== FALSE) {
$i++;
if ($ignoreFirstLine && $i == 1) { continue; }
$rows[] = $data;
}
fclose($handle);
}
return $rows;
}
}
@OneWeb
Copy link

OneWeb commented Apr 19, 2018

I had to

use Symfony\Component\Finder\Finder;

But otherwise all good 👍

@pchelk1n
Copy link

pchelk1n commented Mar 6, 2020

yield

@efleon9
Copy link

efleon9 commented Jun 30, 2021

Thanks!

@dileepn0536
Copy link

It is very useful for the import csv file in a database. Thanks for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment