How to Read an XML File in PHP with SimpleXML

Alternatively, this could be called “How to Read an RSS Feed in PHP with SimpleXML.”  Most of you will be using this code to read an RSS feed and place it on your website (i.e. your Twitter feed).

The code is actually pretty simple.  Just make sure you have SimpleXML on your server.

[[code]]czo3ODpcIjAxLiAkeG1sIMKgIMKgIMKgwqDCoCA9IEBzaW1wbGV4bWxfbG9hZF9maWxlKFwnPGVtPmxvY2F0aW9uIG9mIHhtbCBmaWxle1smKiZdfTwvZW0+XCcpO1wiO3tbJiomXX0=[[/code]][[code]]czo2NjpcIg0KMDIuIGZvciAoJG4gPSAwOyAkbiAmbHQ7IDU7ICRuKyspIHsNCjAzLiAgICR0aXRsZcKgwqDCoMKgwqDCoCA9IFwiO3tbJiomXX0=[[/code]][[code]]czo0MDpcIiR4bWwtJmd0O2NoYW5uZWwtJmd0O2l0ZW1bJG5dLSZndDt0aXRsZTtcIjt7WyYqJl19[[/code]]
04.   [[code]]czozODQ6XCIkZGVzY3JpcHRpb24gPSAkeG1sLSZndDtjaGFubmVsLSZndDtpdGVtWyRuXS0mZ3Q7ZGVzY3JpcHRpb247DQowNS4gICB7WyYqJl19JGd1aWTCoMKgwqDCoMKgwqDCoCA9ICR4bWwtJmd0O2NoYW5uZWwtJmd0O2l0ZW1bJG5dLSZndDtndWlkOw0KMDYuICAgJHB1YkRhdHtbJiomXX1lIMKgIMKgID0gZGF0ZShcImwsIEYgaiwgWSBcXGFcXFxcdCBnOmlBXCIsIHN0cnRvdGltZSgkeG1sLSZndDtjaGFubmVsLSZndDtpdGVtWzB7WyYqJl19XS0mZ3Q7cHViRGF0ZSkpOw0KMDcuIA0KMDguICAgZWNobyBcJyZsdDtwJmd0O1wnIC4gJHRpdGxlIC4gXCcmbHQ7YnIgLyZndDtcJyAuICR7WyYqJl19ZGVzY3JpcHRpb24gLiBcJyZsdDticiAvJmd0O1wnIC4gJGd1aWQgLiBcJyZsdDticiAvJmd0O1wnIC4gJHB1YkRhdGUgLiBcJyZsdDsvcCZne1smKiZdfXQ7XCc7DQowOS4gfVwiO3tbJiomXX0=[[/code]]

As you can see, this short bit of code is extremely simple.  Line 1 is simply calling the XML file.  Line 2 begins a for loop that goes through the first 5 entries in the XML file.  You can change the 5 to any number you want.  Lines 3-6 are taking each element of the items and saving them to a variable.  In line 6 you’ll see I added in a date function to format the date in the RSS feed for output.  Line 8 is writing all the data to the browser.  Of course, you can change the way you want it outputted by simply changing the HTML around the variables.

Very easy to do and easy to adapt to any XML file.

This entry was posted in Uncategorized. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Twitter Updates @BOLDesign