Skip to content

Instantly share code, notes, and snippets.

@adrianalonso
Created January 22, 2016 12:10
Show Gist options
  • 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;
}
}
@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