Created
November 20, 2015 11:37
-
-
Save arth2o/5606b960e29bb9b8df61 to your computer and use it in GitHub Desktop.
Yield PHP load RSS (XML) data
This file contains hidden or 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 | |
$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