WebReference.com - Part 4 of Chapter 10 from Professional PHP4 XML, from Wrox Press Ltd (3/5)
[previous] [next] |
Professional PHP4 XML, Chapter 10: Putting It Together
Using DOM To Write XML Data
The DOM extension is usually used to parse an XML document to the DOM representation, but it can also be used to begin an empty document and add children, sub-children, and sub-sub-children until an XML document is constructed. The dump_mem()
method then allows us to recover the XML document from the DOM tree.
The methods used to insert elements and attributes to the DOM tree are very useful when constructing XML documents.
This is the same code we used in the manual writing approach, but here we use DOM calls to generate the XML file:
$parser = new ParseToDoTxt();
$parser->ParseFile("todo.txt");
$persons = $parser->GetPersons();
//$doc = domxml_new_doc("1.0");
$doc = new_xmldoc("1.0");
$node = $doc->create_element("to-do");
$root = $doc->add_child($node);
foreach ($persons as $person => $tasks) {
$node_person = $doc->create_element("person");
$node_name = $doc->create_element("name");
$node_name_text = $doc->create_text_node($person);
$node_name->add_child($node_name_text);
$node_tasks = $doc->create_element("tasks");
foreach ($tasks as $task) {
$node_task = $doc->create_element("task");
$node_task_text = $doc->create_text_node($task);
$node_task->add_child($node_task_text);
$node_tasks->add_child($node_task);
}
$node_person->add_child($node_name);
$node_person->add_child($node_tasks);
$root->add_child($node_person);
}
$xml = $doc->dump_mem();
print ($xml);
Using DOM we may skip calling the XmlEntities()
function, since the DOM class is supposed to construct valid well-formed XML documents from our text.
In many ways using DOM is the best way to generate an XML file. The only problem we may face is that the PHP DOM extension is not very stable and changes to the extension may require changing programs that use it if we want to update our PHP installation.
Here are some of the advantages and disadvantages of using DOM:
Advantages | Disadvantages |
---|---|
Entities are generated by the DOM extension | Sometimes just manual writing is easier |
Methods to ease the creation of complex XML documents | Programs depend on the unstable DOM extension of PHP |
Code is easier to maintain |
[previous] [next] |
Created: September 3, 2002
Revised: September 3, 2002
URL: https://webreference.com/programming/php/php4xml/chap10/4/3.html