domxml_open_mem(file_get_contents('quotes.xml')
When using PHP 4, the create_element()
method creates a new element. You can set its content with set_content()
and attributes with set_attribute()
. Finally, you access the root element of the XML file with document_element()
and then call append_child()
. Finally, dump_mem()
returns the whole XML file as a string so that you can save it to the hard diskor you can use dump_file()
to let PHP do the saving. However, note that dump_file()
uses an absolute path, so you might be better off with PHP's own file-handling functions.
Creating XML with DOM
<?php require_once 'stripFormSlashes.inc.php'; $dom = domxml_open_mem(file_get_contents ('quotes.xml')); $quote = $dom->create_element('quote'); $quote->set_attribute('year', $_POST['year']); $coding = $dom->create_element('coding'); $coding->set_content($_POST['quote']); $author = $dom->create_element('author'); $author->set_content($_POST['author']); $quote->append_child($coding); $quote->append_child($author); $root = $dom->document_element(); $root->append_child($quote); file_put_contents('quotes.xml', $dom->dump_mem()); echo 'Quote saved.'; ?>
The preceding code saves author, quote, and year in an XML document, appending to the data already there.
Using DOM in PHP5 to Write XML
$dom = new DOMDocument();
When using PHP 5, the code changes a bit, but most of it is changing to studly caps.
Creating XML with DOM in PHP5
<?php require_once 'stripFormSlashes.inc.php'; $dom = new DOMDocument(); $dom->load('quotes.xml'); $quote = $dom->createElement('quote'); $quote->setAttribute('year', $_POST['year']); $coding = $dom->createElement('coding'); $codingText = $dom-> createTextNode($_POST['quote']); $coding->appendChild($codingText); $author = $dom->createElement('author'); $authorText = $dom-> createTextNode($_POST['author']); $author->appendChild($authorText); $quote->appendChild($coding); $quote->appendChild($author); $dom->documentElement->appendChild($quote); $dom->save('quotes.xml'); echo 'Quote saved.'; ?>
PHP 5's DOM extension does not offer something like PHP 5's set_content()
, so you have to define the text values of the nodes using the createTextNode()
method, as shown in the preceding code.