Introducing simpleXML Parser

SimpleXML is a tree-based parser. SimpleXML provides an easy way of getting an element's name, attributes and textual content if you know the XML document's structure or layout. SimpleXML turns an XML document into a data structure you can iterate through like a collection of arrays and objects. Compared to DOM or the Expat parser, SimpleXML takes a fewer lines of code to read text data from an element.

In the last tutorial, I gave an introduction to XML parsers in PHP and let us recollect key information from that. SimpleXML parser,

  • requires libxml extension
  • is an easy and simple to use tool for XML parsing
  • requires PHP 5 or above
  • is a tree-based parser
  • is interoperable with DOM parsers and can parse DOM formatted XML documents.
  • Installation

    As of PHP 5, the SimpleXML functions are part of the PHP core. No installation is required to use these functions.

    PHP SimpleXML Parser Example -

    Now, its time to experiment the above SimpleXML functions to parse a XML document. First, we should create XML document. Let us take a simple XML document,

    Example -

    Adding Child Element using SimpleXML Parser

    To add a child element to a node in a XML document, we use addChild() of SimpleXMLElement class.

    Example -