Skip to content

Instantly share code, notes, and snippets.

@MikSDigital
Created May 2, 2017 15:10
Show Gist options
  • Save MikSDigital/cbb8b59cfc308f45b586e400770880f4 to your computer and use it in GitHub Desktop.
Save MikSDigital/cbb8b59cfc308f45b586e400770880f4 to your computer and use it in GitHub Desktop.
another example of CSV file reading/parsing
<?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('csv:read')
->setDescription('Import csv file');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$csv = $this->parseCSV();
foreach ($csv as $item => $value) {
// $output->writeln($value[2]); // $value[0] - id, $value[1] - slug, $value[2] - content
// $output->writeln('');
$this->bigString .= $value[2];
//var_dump($value[2]);
$doc = new \DOMDocument();
@$doc->loadHTML($value[2]);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag)
{
// var_dump( $tag->getAttribute('src'));
//
$http = strpos($value[2], 'C:');
if($http)
{
$this->matches[$value[1]] = $tag->getAttribute('src');
}
}
}
// var_dump($this->bigString);
var_dump($this->matches);
//
// $doc = new \DOMDocument();
// @$doc->loadHTML($this->bigString);
// $tags = $doc->getElementsByTagName('img');
//
// foreach ($tags as $tag)
// {
// var_dump( $tag->getAttribute('src'));
// }
}
/**
* @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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment