PHP code example of benkle / feed-parser

1. Go to this page and download the library: Download benkle/feed-parser library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

benkle / feed-parser example snippets


$reader = new \Benkle\FeedParser\Reader();
$feed = $reader->read(file_get_contents('http://xkcd.com/atom.xml'));

echo $feed->getTitle() . PHP_EOL;
foreach ($feed->getItems() as $item) {
    echo "\t" . $item->getTitle() . PHP_EOL;
}

class MyRule implements \Benkle\FeedParser\Interfaces\RuleInterface {
    public function canHandle(\DOMNode $node, \Benkle\FeedParser\Interfaces\NodeInterface $target)
    {
        return $node->nodeName == 'title' && $target instanceof \Benkle\FeedParser\Interfaces\ChannelInterface;
    }

    public function handle(\Benkle\FeedParser\Parser $parser, \DOMNode $node, \Benkle\FeedParser\Interfaces\NodeInterface $target)
    {
        /** \Benkle\FeedParser\Interfaces\ChannelInterface $target */
        $target->setTitle($node->nodeValue);
    }
}

/** @var \Benkle\FeedParser\Interfaces\StandardInterface $standard */
foreach ($reader->getStandards() as $standard) {
    $standard->getRules()->add(new MyRule(), 5); // Rules are ordered by priority
}

class MyStandard implements \Benkle\FeedParser\Interfaces\StandardInterface {
    use \Benkle\FeedParser\Traits\WithParserTrait;
    use \Benkle\FeedParser\Traits\WithRuleSetTrait;

    public function __construct()
    {
        $this->getRules()->add(new MyRule(), 5);
    }

    public function newFeed()
    {
        return new \Benkle\FeedParser\Feed();
    }

    public function getRootNode(\DOMDocument $dom)
    {
        return $dom->getElementsByTagName('feed')->item(0);
    }


    public function canHandle(\DOMDocument $dom)
    {
        return $dom->getElementsByTagName('feed')->length > 0;
    }
}

$reader->getStandards()->add(new MyStandard(), 5);

$reader->setDomParser(new class implements \Benkle\FeedParser\Interfaces\DOMParserInterface {
    public function parse($source)
    {
        $parser = new \MyFancy\DomParser();
        return $parser->parse($source);
    }
});

$reader->setDomParser(
    new \Benkle\FeedParser\DOMParsers\FallbackStackParser(
        new \Benkle\FeedParser\DOMParsers\PHPDOMParser(),
        new \Benkle\FeedParser\DOMParsers\MastermindsHTML5Parser()
    )
);

$reader = new \Benkle\FeedParser\BareReader();
$reader->setDomParser(new \Benkle\FeedParser\DOMParsers\PHPDOMParser());
$reader->getStandards()->add(new \Benkle\FeedParser\Standards\RSS\RSS20Standard());