Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony how to parse RSS feed on Twig

For example, in PHP a way to parse RSS feed could be:

<?php
$rss = simplexml_load_file('http://blog.wordpress_site.com/feed/');

{{ rss }}

foreach ($rss->channel->item as $item) {
    echo $item->title;
    echo $item->link;
    echo $item->description;
    echo $item->guid;
}
?>

How can I have this on Twig?

UPDATE: Thanks to the reply I got it. Now it gets this by item but not some fields like image, category or text of the post:

SimpleXMLElement {#955 ▼
  +"title": "Website. Description of the website"
  +"link": "http://blog.website.com/liktothepost"
  +"pubDate": "Fri, 17 Feb 2017 07:56:43 +0000"
  +"category": SimpleXMLElement {#1131}
  +"guid": "http://blog.website.com/?p=400"
  +"description": SimpleXMLElement {#953}
}
like image 346
jmunozco Avatar asked Oct 29 '22 11:10

jmunozco


1 Answers

You would create a controller with an action to pass the object to your Twig file that you want to render like so:

public function viewRSSAction(Request $request){
    $rss = simplexml_load_file('http://blog.wordpress_site.com/feed/');

    return $this->render('my_rss.html.twig', array(
            'rss' => $rss,
    ));
}

Then your my_rss.html.twig might look like this:

{% for item in rss %}
    {{ item.title }}
    {{ item.link }}
    {{ item.description }}
    {{ item.guid }}
{% endfor %}
like image 57
Alvin Bunk Avatar answered Nov 15 '22 07:11

Alvin Bunk