Using DOM in PHP 4 to Write XML

Apart from the read access, it is also possible to build complete XML documents from the ground up using PHP's DOM support. This might look a bit clumsy; however, it works very well when you have to automatically parse a lot of data.


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

  require_once '';
  $dom = domxml_open_mem(file_get_contents
  $quote = $dom->create_element('quote');
  $quote->set_attribute('year', $_POST['year']);
  $coding = $dom->create_element('coding');
  $author = $dom->create_element('author');
  $root = $dom->document_element();
  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

  require_once '';
  $dom = new DOMDocument();
  $quote = $dom->createElement('quote');
  $quote->setAttribute('year', $_POST['year']);
  $coding = $dom->createElement('coding');
  $codingText = $dom->
  $author = $dom->createElement('author');
  $authorText = $dom->
  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.

by BrainBellupdated