Extract rss feed from a url with simplexml_load_file

simplexml_load_file interprets an XML file into an object. This tutorial describes how to parse an XML document or RSS feed that follows a known schema.

We can directly iterate over SimpleXML’s elements / items using foreach.

Read RSS Feed from a URL

$rss = simplexml_load_file($url);

foreach ($rss->channel as $channel){
 foreach ($channel->item as $item){
  echo $item->link.'<br>';
  echo $item->title.'<br>';
  echo $item->description.'<br>';

Parsing an XML file

SimpleXML is also useful to read a configuration file written in XML or process the result of a REST request.

Here’s an example of book store in XML.

$books = simplexml_load_file('bookstore.xml');
foreach ($books as $book) {
 echo $book->name.'<br>';
 echo $book->price.' $<br>';
 echo $book->date.'<br>';
 echo '<b>Authors:</b><br>';
 foreach ($book->author as $author){
  echo $author->firstName.'<br>';
  echo $author->lastName.'<br>';
 echo '<hr>';

Sample bookstore.xml file to parse.

<?xml version="1.0"?>
  <name>PHP Book</name>
  <name>XML Book</name>
   <firstName>First Name</firstName>
   <lastName>Last Name</lastName>
by BrainBellupdated