Skip to content

Instantly share code, notes, and snippets.

@arth2o
Created November 20, 2015 11:37
Show Gist options
  • Save arth2o/5606b960e29bb9b8df61 to your computer and use it in GitHub Desktop.
Save arth2o/5606b960e29bb9b8df61 to your computer and use it in GitHub Desktop.
Yield PHP load RSS (XML) data
<?php
$rssUrl = "http://arth2o.com/rss.xml";
/**
* Load xml use PHP yield Generator
**/
class GetRss
{
private $url;
private $element;
public function __construct($url, $element)
{
$this->url = $url;
$this->element = $element;
}
public function streamXml()
{
$reader = new XMLReader();
$reader->open($this->getUrl());
while (true) {
// Skip to next element
while (! ($reader->nodeType == XMLReader::ELEMENT && $reader->name == $this->getElement())) {
if (! $reader->read()) break(2);
}
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == $this->getElement()) {
yield simplexml_load_string($reader->readOuterXml());
$reader->next();
}
}
}
public function getUrl()
{
return $this->url;
}
public function getElement()
{
return $this->element;
}
}
$xmlReader = new GetRss($rssUrl, 'item');
foreach($xmlReader->streamXml() as $itemXml) {
echo $itemXml->title . "\n<br />";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment