PHP

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"?>
<books>
 <book>
  <name>PHP Book</name>
  <date>20016-09-24</date>
  <price>5.00</price>
  <author>
   <firstName>FName</firstName>
   <lastName>LName</lastName>
  </author>
  <author>
   <firstName>FName2</firstName>
   <lastName>LName2</lastName>
  </author>
 </book>
 <book>
  <name>XML Book</name>
  <date>20016-12-24</date>
  <price>10.00</price>
  <author>
   <firstName>First Name</firstName>
   <lastName>Last Name</lastName>
  </author>
 </book>
</books>
by BrainBellupdated
Advertisement: