Skip to content

Instantly share code, notes, and snippets.

@houssemz
Last active July 1, 2018 13:21
Show Gist options
  • Save houssemz/a3c79ae86d373c1e2e5fa7b964bf71b0 to your computer and use it in GitHub Desktop.
Save houssemz/a3c79ae86d373c1e2e5fa7b964bf71b0 to your computer and use it in GitHub Desktop.
The Document Object Model extension allows to operate on XML documents through the DOM API

The XML DOM Parser :

The DOM parser is a tree-based parser.

Load and Output XML :

Exp :

<!-- file.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

print $xmlDoc->saveXML(); 

# output
/*
<?xml version="1.0" encoding="UTF-8"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>
*/
?>

SimpleXML and DOM :

  • simplexml_import_dom() Converts to SimpleXML object from DOM node
<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');

$s = simplexml_import_dom($dom);

echo $s->book[0]->title; // blah
  • dom_import_simplexml() Converts to DOM element from a SimpleXML object
<?php
$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

$dom_sxe = dom_import_simplexml($sxe);

$dom = new DOMDocument('1.0');
// Import the node, and all its children, to the document
$dom_sxe = $dom->importNode($dom_sxe, true);
// And then append it to the "<root>" node
$dom_sxe = $dom->appendChild($dom_*/sxe);

echo $dom->saveXML();

# output
/*
<?xml version="1.0"?>
<books><book><title>blah</title></book></books>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment