Custom logger and middleware stack - simplepie/simplepie-ng GitHub Wiki
Works as of commit 3ff70d6926.
use GuzzleHttp\Psr7;
use Monolog\Handler\ErrorLogHandler;
use Monolog\Logger;
use Psr\Log\LogLevel;
use SimplePie\HandlerStack;
use SimplePie\Middleware\Json\JsonFeed;
use SimplePie\Middleware\Xml\Atom;
use SimplePie\Middleware\Xml\Rss;
use SimplePie\SimplePie;
// Configure the logger.
$logger = new Logger('SimplePie');
$logger->pushHandler(new ErrorLogHandler(
ErrorLogHandler::OPERATING_SYSTEM,
LogLevel::DEBUG,
true,
false
));
// Configure the middleware stack.
$middleware = (new HandlerStack())
->append(new JsonFeed(), 'jsonfeed')
->append(new Atom() , 'atom10')
->append(new Rss() , 'rss20')
;
// Instantiate SimplePie.
$simplepie = (new SimplePie())
->setLogger($logger)
->setMiddlewareStack($middleware)
;
// Pass a PSR-7 stream to SimplePie for parsing.
$stream = Psr7\stream_for(file_get_contents(__DIR__ . '/releases.atom'));
// Specifically parses XML.
// Only applies the middleware that is registered as supporting XML feed types.
$parser = $simplepie->parseXml($stream, true);
// Reference the top-level feed object
$feed = $parser->getFeed();
// By default, all nodes return a `SimplePie\Type\Node` object with a `toString()` method defined.
// You can also handle various allowed serializations differently.
foreach ($feed->getItems() as $item) {
switch ($item->getTitle()->getSerialization()) {
case 'xhtml':
// Custom XML stuff...
break;
case 'text':
case 'html':
default:
echo $item->getTitle()->getValue();
}
}