In the document object model (DOM) implementation in PHP, The DOMDocument class is the starting point. The DOMDocument helps to create, load, and save XML documents in PHP.
We can instantiate an empty document using the new keyword as:
1 | $domdoc = new DOMDocument('1.0', 'ISO-8859-1'); |
The optional 1.0 parameter specifies the XML 1.0 specification. The ISO-8859-1 is the optional encoding format.
Using the $domdoc object, a tree can either be created or be loaded from an XML document. You can load a document from a string containing the XML or from a remote resource using the loadXML method.
1 2 3 4 5 6 | $xmldata = '<?xml version="1.0"?> <main> <sub>contents</sub> </main>'; $domdoc->loadXML($xmldata, LIBXML_NOBLANKS); |
The newline characters, tabs, and spaces are removed in this case because of the use of the parser option LIBXML_NOBLANKS.
More examples of loading XML files in PHP:
File located in current script directory:
1 | $domdoc->load('xmlsampledata.xml', LIBXML_NOBLANKS); |
File loaded using absolute path
1 | $domdoc->load('file:///tmp/xmlsampledata.xml', LIBXML_NOBLANKS); |
File loaded from http://www.w3mentor.com/xmlsampledata.xml
1 | $domdoc->load('http://www.w3mentor.com/xmlsampledata.xml', LIBXML_NOBLANKS); |
In PHP5, the equivalent to the LIBXML_NOBLANKS option is the preserveWhiteSpace property.
Removing blanks under PHP5:
1 2 3 | $domdoc = new DOMDocument(); $domdoc->preserveWhiteSpace = FALSE; $domdoc->load('xmlsampledata.xml'); |