XML

DOM

Read

DOMDocument->load(filename)               // Loads XML from a file
DOMDocument->loadXML(string xml-source) // Loads XML from a string

Write

DOMDocument->save(filename)     // Saves the internal XML tree to a file
string DOMDocument->saveXML() // Returns the internal XML tree as a string

Parse

<?xml version="1.0" encoding="UTF-8"?>
<data>
<node name="zaphod">This is some text.</node>
</data>

...

<?php
$doc = DOMDocument::load("data.xml");
$node_element = $doc->getElementsByTagName('node')->item(0);
$name = $node_element->getAttribute('name');
$text = $node_element->nodeValue;
?>

Validate

DTD
bool DOMDocument->validate()   // Validates the document based on its DTD
<?php
// Validate using a DTD
$doc = DOMDocument::load("data-dtd.xml");
$doc->validate() or print
?>
XML Schema
bool DOMDocument->schemaValidate(schema-filename)              // Validates a document based on a schema
bool DOMDocument->schemaValidateSource(string schema-source) // Validates a document based on a schema
<?php
// Validate using XML Schema
$doc = DOMDocument::load("data-xsd.xml");
$doc->schemaValidate("data.xsd") or print "Validation of XML using XSD unsuccessful";
print $doc->saveXML();
?>
RELAX NG
bool DOMDocument->relaxNGValidate(relax-ng-filename)              // Performs relaxNG validation on the document
bool DOMDocument->relaxNGValidateSource(string relax-ng-source) // Performs relaxNG validation on the document
<?php
// Validate using RELAX NG
$doc = new DOMDocument();
$doc->load("data-rng.xml");
$doc->relaxNGValidate("data.nsd") or print "Validation of XML using RELAX NG unsuccessful";
print $doc->saveXML();
?>

SAX

  • User-defined callback functions are called for each tag or section of text encountered.