Parse XML in PHP – Introduction
In PHP, parsing XML file is done using different extensions available. Using these extensions we can access, modify, validate and do much more things on a XML document.
Parsing techniques used by these PHP XML parser extensions are, tree-based, stream-based and event-based parsing. In this article, we are going to see an introduction for these PHP extensions.
XML Parser Extensions
Following listing shows XML parser extensions available in PHP core. All these extensions requires libxml extension and which is enabled by default.
1. SimpleXML Parser
- SimpleXML parser is a tree-based parser.
- As rightly named, this parser is used to parse simple XML file (not too lengthy and without complex node structure).
- It converts XML file and returns corresponding SimpleXMLElement object.
- We can load XML file or document as string for SimpleXML functions. For example, simplexml_load_file() accepts XML file path and simplexml_load_string() requires string.
2. DOM Parser
- DOM parser extension in PHP is used to handle high complex XML file.
- It is used as an interface to access and modify given XML document.
- This is also tree-based parser as like as SimpleXML.
- As of PHP 5 it is upgraded from older version of DOM with domxml.
- DOM parser extension is using utf-8 character encoding.
Both SimpleXML and DOM parsers are interoperable. Meaning that, the DOM function will accept SimpleXML object array to covert it into DOM format. Similarly, SimpleXML function will accept DOM formatted XML document to convert into object array.
3. XML Parser
- This is an event based SAX parser.
- It is faster than the above two, since is not loading the whole XML document into memory to parse.
- It creates XML parsers, implements XML manipulation classes of Expat parser library.
- It supports three type of character encoding ISO-8859-1, US-ASCII and UTF-8.
- While using this extension, we need to create XMLParser instance (parser handle) to access its member functions.
- This parser extension can work with namespaced XML.
4. XML Reader
- It is a stream-based parser and also known as pull parser, since it pulls data from given XML file.
- It is the best choice of PHP XML extensions for reading a XML document, why because it,
- is faster
- works with high complex XML document
- supports XML validation
- We should have PHP version 5.1 and above to use this extension.