Skip to content

Instantly share code, notes, and snippets.

@MikSDigital
Created May 2, 2017 06:00
Show Gist options
  • Save MikSDigital/630d6db8822410a84ac578b53c7896fa to your computer and use it in GitHub Desktop.
Save MikSDigital/630d6db8822410a84ac578b53c7896fa to your computer and use it in GitHub Desktop.
Symfony parseCSV command example (diffrent approach)
<?php
namespace AppBundle\Command;
use Symfony\Component\Console\Command\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;
use Symfony\Component\Finder\Finder;
use Symfony\Component\DomCrawler\Crawler;
class TestCommand extends ContainerAwareCommand
{
private $csvParsingOptions = array(
'finder_in' => __DIR__,
'finder_name' => 'test.csv',
'ignoreFirstLine' => false
);
private $matches = [];
private $bigString = '';
protected function configure()
{
$this->setName('test')
->setDescription('Import csv file');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$csv = $this->parseCSV();
foreach ($csv as $item => $v) {
// $output->writeln($v[2]); // $v[0] - id, $v[1] - slug, $v[2] - content
// $output->writeln('');
$this->bigString .= $v[2];
}
var_dump($this->bigString);
$crawler = new Crawler($this->bigString);
foreach ($crawler as $domElement) {
var_dump($domElement->nodeName);
}
$output->writeln('Hello! This is result.');
}
/**
* @throws \Exception
*/
private function parseCSV()
{
$ignoreFirstLine = $this->csvParsingOptions['ignoreFirstLine'];
$finder = new Finder();
$finder->files()
->in($this->csvParsingOptions['finder_in'])
->name($this->csvParsingOptions['finder_name'])
->files();
foreach ($finder as $file) {
$csv = $file;
}
if (empty($csv)) {
throw new \Exception("NO CSV FILE");
}
$rows = [];
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;
}
private function getImageSRC($content)
{
$pattern = "/src=([^\\\"]+)/";
preg_match_all($pattern, $content, $this->matches);
return $this->matches;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment