I can’t believe I’m spending so much time on this XML subject (granted it’s my weakest area as I haven’t had a chance to use it yet). I think tomorrow I’ll implement the XML manipulation of iTunes AppStore data (that will make a LOT of people happy).
Anyway, it’s important to note, when we get into this section, that the DOM is apparently interoperable with the SimpleXML object. This is good to know. The method to do so is:
-
$sxml = simplexml_load_file('text.xml');
-
$node = dom_import_simplexml($sxml);
-
-
$dom = new DOMDocument();
-
$dom->importNode($node, true);
-
$dom->appendChild($node);
-
-
// DOM to SimpleXML
-
$dom = new DOMDocument();
-
$dom->load('test.xml');
-
-
$sxml = simplexml_import_dom($dom);
Okay, well before we jump the gun with the DOM syntax, here is the basic code to open a new DOM object:
-
$dom = new DomDocument();
-
$dom->load("library.xml");
-
-
// Load from a string
-
$dom = new DomDocument();
-
$dom->load($xml);
-
-
// Save the document
-
$dom->save('library.xml');
-
-
// Output to the screen
-
$dom->saveXML();
XPath Queries are mode advanced than SimpleXML and can be a little more work:
-
-
$result = $xpath->query("//title/text()");
-
-
// Single access
-
echo $result->item(0)->data;
-
-
// Loop
-
foreach ($result as $book) {
-
echo $book->data;
-
}
Modification of data is a little bit more complex than before. In DOM, the objects you create create are not automatically assigned to the XML and have to be appended later.
-
$book = $dom->createElement("book");
-
// Add some attributes
-
$book->setAttribute("isbn", "12345");
-
-
// Create the title child
-
$title = $dom->createElement("title");
-
// Add text to it
-
$text = $dom->createTextNode("Harry Potter");
-
-
// Add the text to the title, and the title to the book
-
$title->appendChild($text);
-
$book->appendChild($title);
-
-
// Add the book to the XML document itself
-
$dom->documentElement->appendChild($book);
Remember in SimpleXML, it was impossible to fully remove a node. Well, here is the possible version in DOM.
-
$xpath = new DOMDocument();
-
$result = $xpath->query("//text");
-
-
// To remove an attribute, it's easy
-
$result->item(0)->removeAttribute('type');
-
-
// But here is the confusing part: to remove the node,
-
// we need to ask its parent to remove their child that is the node.
-
$result->item(0)->parentNode->removeChild($result->item(0));
-
-
// And if we needed to clear CDATA, we can use this function
-
$result = $xpath->query('text()');
-
$result->item(0)->deleteData(0, $result->item(0)->length);
Tomorrow will be the Security chapter (almost done!!) and I’ll try to write up the PHP iTunes AppStore code (since it involves XML).

