[Previous] [TOC] [Next]


Using DOM in PHP 5 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 (dom-write5.php; excerpt)
<?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.';
?>

NOTE

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.



[Previous] [TOC] [Next]