PHP DomDocument Examples and Quick Reference

PHP DomDocument Examples and Quick Reference

Last updated:

load an xml file

$path = '/path/to/your/file.xml';
$xml_data = file_get_contents($path);
$dd->loadXML($xml_data);

load an xml file ignoring blanks

this is useful because generally you don't want to take spaces between nodes into account. (other spaces are still parsed)

$path = '/path/to/your/file.xml';
$xml_data = file_get_contents($path);
$dd->loadXML($xml_data,LIBXML_NOBLANKS);

fetch the root node

suppose the root node in your xml file is <foo>

$path = '/path/to/your/file.xml';
$xml_data = file_get_contents($path);
$dd->loadXML($xml_data,LIBXML_NOBLANKS);
$root_node = $dd->getElementsByTagName('foo')->item(0);

dump the XML to the screen

var_dump-style dumping for XML files

$dd = new DOMDocument;
$dd->loadXML($xml_data,LIBXML_NOBLANKS);
echo htmlspecialchars($dd->saveXML());
exit;