Created
January 22, 2016 12:10
-
-
Save adrianalonso/69733bf2527a2ef56b32 to your computer and use it in GitHub Desktop.
Symfony Command Import CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is very useful for the import csv file in a database. Thanks for sharing.