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

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Naveen Balani, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}