Skip to main content

Introduction to PHP 5 and SimpleXML

By August 15, 2019March 24th, 2020Website Development

XML is useful for any number of reasons – syndicating articles in RSS feeds, releasing data through an API, communicating between different applications, just to name a few.

XML is simple to write, but until recently the major hump to get over was how to read the XML. PHP 4 offered some XML parsing capabilities, but for the most part you had to write your own parser. PHP 5 introduced a great new utility – SimpleXML. It was a simple but powerful built-in XML parser.

What Does SimpleXML Do?

SimpleXML is a DOM-like library for reading an XML file or string. It reads a file or string and then creates a web of inter-connected objects.

Each SimpleXML object represents one element in the XML file. It has references to its parent element and child elements, as well as an array containing all of the attributes of that element.

You can easily navigate the XML tree by starting with a parent object and then referencing each of the child nodes as a property or method of that parent. For example, you could access a link element inside an item element inside a channel element like this – $xml- gt;channel- gt;item[0]- gt;link.

It’s also simple to create and insert new nodes with SimpleXML. The addChild() method allows you to add a child element at any point.

What Can You Do With SimpleXML?

Well, pretty much anything you want to do with XML. SimpleXML will make a host of tasks much simpler to perform.

Creating Your Own Feed. Without SimpleXML, you would have to hardcode an XML string to create an RSS feed for your site. With SimpleXML, you can start with a basic feed – an rss element – and then simply add children to it with a bunch of addChild() calls. Here’s a tutorial on how to use SimpleXML to create your feed.

Computer code on screens

Syndicating a Remote Feed. With SimpleXML, it is easy to open a remote xml file (like an RSS feed), parse the contents, and display it on your website. With this, you can add valuable content – in the way of links and descriptions to other articles – without taking a lot of time. Take a look at this walkthrough on syndicating an RSS feed on your site.

Harvesting Data from Other Sources. There are a lot of places on the ‘net that stream data through XML. For example, Digg opened access to its vault of stories and data through an XML driven API. You can use SimpleXML to access this API and display a random Digg story on your website. By using the SimpleXML @attributes array, you can also access data from the World of Warcraft Armory.

Look around, and you’ll find something to use XML for. Chances are, using SimpleXML will make it, well, simpler.