Tuesday, September 22, 2009

PHP DOM XML Example - Document Object Model

This is a simple php 5, DOM/XML example illustrating the basics such as creating tags, name/vaule pairs and text nodes using createElement, appendChild , setAttribute etc. The XML is displayed on the console, but could just as well be the response to an XMLHttpRequest.

First lets have a look at the example. It's self explanatory.
 1. <?php 
 2. 
 3. $dom = new DomDocument('1.0');
 4. $dom->formatOutput = true;
 5. 
 6. $carroot = $dom->createElement("car-root");
 7. $dom->appendChild($carroot);
 8. 
 9. $car = $dom->createElement("car");
10. $car->setAttribute("model","Ferrari F60");
11. $carroot->appendChild($car);
12. 
13. $description = $dom->createElement("description");
14. $description->appendChild($dom->createTextNode("Enzo Ferrari"));
15. $car->appendChild($description);
16. 
17. $engine = $dom->createElement("engine");
18. $engine->appendChild($dom->createTextNode("V12"));
19. $car->appendChild($engine);
20. 
21. echo $dom->saveXml();
22. ?>
Hide line numbers

No comments: