Приглашаем посетить
Ларри (larri.lit-info.ru)

Using DOM in PHP 4 to Write XML

Previous
Table of Contents
Next

Using DOM in PHP 4 to Write XML

domxml_open_mem(file_get_contents('quotes.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 (dom-write4.php; excerpt)
<?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']);
  $phrase = $dom->create_element('phrase');
  $phrase->set_content($_POST['quote']);
  $author = $dom->create_element('author');
  $author->set_content($_POST['author']);
  $quote->append_child($phrase);
  $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.


Previous
Table of Contents
Next