Nowadays, RSS Feed is commonly used in all sites which provide you the latest news or information of the site.
You must have to take care if you are parsing RSS feeds which are not your own and you have to have permission to use the feed.
Let’s start to understand code
we are going to understand for WordPress so first of all you need to include below file if you are using the custom page.
1 2 3 |
SimpleXML provides is a simple way of getting an XML element and converts an XML document into a SimpleXMLElement object.so here we will use simpleXML to extract data.
1 2 3 4 5 6 7 8 9 10 11 | $data = wp_remote_retrieve_body(wp_remote_get($url, array( 'timeout' => 30 ) )); $dom->loadXML($data); if (!$dom) { exit; } $xml = simplexml_import_dom($dom); $xml_data = $xml->channel->item; |
Here,we have used wordpress function wp_remote_retrieve_body which retrieve body from the remote servers and body of the page can be accessed through wp_remote_get/wp_remote_post method in wordpress. Then we have used DOMDocument which represents the object of entire XML document and loadXML which is used to parse an XML string when uses the DOMDocument object.
simplexml_import_dom is uses a node of a DOM document and convert it into a SimpleXML node.It will parse the data received & return it as a SimpleXML Object.
1 2 3 4 5 | foreach($xml_data as $key => $val) { echo $val->title; } |
By the end, I suggest you to read:
To extract RSS XML feed in PHP
WordPress: To add custom post type into RSS
How to fetch and display a feed in WordPress?
As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.
Comments (4)