$ composer create-project suncat/console-commands ./cmd
$ cd cmd # ,
app/ console # src/ # psr-0 Command/ # vendor/ #
$ app/console list
$ app/console generate
Please enter the name of the command class: NewsInternetCommand
Generated new command class to "./cmd/src/Command/NewsInternetCommand.php"
$ composer require kriswallsmith/buzz 0.9
// ./src/Parser/YandexRSSNewsParser.php namespace Parser; use Buzz\Client\FileGetContents; use Buzz\Message\Request; use Buzz\Message\Response; use DOMDocument; use DOMXPath; class YandexRSSNewsParser { private $method; private $host; /** * Construct */ public function __construct() { $this->method = 'GET'; $this->host = 'http://news.yandex.ru'; } /** * Get news * * @param $resource * * @return mixed */ public function getNews($resource) { // content $xml = $this->getData($resource); if (false === $xml) { return array(); } $doc = new DOMDocument(); @$doc->loadXML($xml); $xpath = new DOMXpath($doc); // items $items = $xpath->query('.//item'); $news = array(); foreach ($items as $item) { $news[] = array( 'datetime' => $xpath->evaluate("./pubDate", $item)->item(0)->nodeValue, 'title' => $xpath->evaluate("./title", $item)->item(0)->nodeValue ); } return $news; } /** * Get data * * @return mixed */ protected function getData($resource) { $request = new Request($this->method, $resource, $this->host); $response = new Response(); $client = new FileGetContents(); // processing get data $attempt = 0; do { if ($attempt) { sleep($attempt); } try { $client->send($request, $response); } catch (\Exception $e) { continue; } } while (false === ($response instanceof Response) && ++$attempt < 5); if (false === ($response instanceof Response) || false === $response->isOk()) { return false; } $data = $response->getContent(); return $data; } }
// ./src/Command/NewsInternetCommand.php namespace Command; use Parser\YandexRSSNewsParser; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * NewsInternetCommand */ class NewsInternetCommand extends Command { /** * Configuration of command */ protected function configure() { $this ->setName("news:internet") ->setDescription("Command for parsing internet news") ; } /** * Execute command * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $parser = new YandexRSSNewsParser(); $output->writeln("<info>Start parsing</info>\n")); // News $news = $parser->getNews('/internet.rss'); foreach ($news as $item) { $output->writeln(sprintf("<info>[%s]</info> <comment>%s</comment>", $item['datetime'], $item['title'])); } $output->writeln("\n<info>Done!</info>")); } }
$ app/console news:internet
Source: https://habr.com/ru/post/173553/
All Articles