Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Parsing XML data in PHP

DZone's Guide to

Parsing XML data in PHP

· Web Dev Zone ·
Free Resource

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

If you are planning to deal with XML data in PHP , for instance parsing an RSS feed or pattern matching (finding images or elements in an XHTML) , than probably you need an XML library which extracts the data for you.

The SimpleXML extension provides a very intuitive API to convert XML to an object and traverse elements easily.The only disadvantage is that it loads entire document in memory, so for very large XML files, performance could be an issue.

If performance is a consideration, you can go with XMLReader , which is an XML pull parser, which doesn’t load entire document in memory, instead it traverses each node on the way.

There are many special purpose libraries available, like simple pie (which is used by wordpress internally for RSS feeds) but I found it too overloaded while dealing with simple fields and didn’t offer XPATH capability to get required nodes quickly and you end up dealing with pattern matching capability with simple pie.
The following code uses simple xml and fetches the latest RSS feeds from my website. I have used curl library to deal with http connections, as its more secured and supported on my hosting server.

<?php
 
function load_file($url) {
$ch = curl_init($url);
#Return http response in string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xml = simplexml_load_string(curl_exec($ch));
return $xml;
}
 
$feedurl = 'http://naveenbalani.com/index.php/feed/';
$rss = load_file($feedurl);
 
foreach ($rss->channel->item as $item) {
echo "<h2>" . $item->title . "</h2>";
echo "<p>" . $item->description . "</p>";
}
 
?>

 

Check out the script output as -  http://naveenbalani.com/util/php/rss.php

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}