--- /dev/null
+<?php
+
+function XML_Template_process_file($filename, $obj, $clean = 1)
+{
+ $doc = domxml_open_file($filename);
+ XML_Template_process($doc, $obj, $clean);
+ return $doc;
+}
+
+function XML_Template_process($node, $obj, $clean = 1, $nsup = array())
+{
+ if (!is_array($obj)) { # overwrite
+ foreach ($node->child_nodes() as $child) {
+ $node->remove_child($child);
+ }
+ $doc = $node->owner_document();
+ $node->add_child($doc->create_text_node($obj));
+ # handle overwrite with a DOM object here
+ } else if (is_associative_array($obj)) { # substitute
+ foreach ($node->child_nodes() as $child) {
+ $processed = false;
+
+ if ($child->node_type() == XML_ELEMENT_NODE) {
+ $tag = $child->node_name();
+ $attrs = $child->attributes();
+ if ($attrs != null) {
+ foreach ($child->attributes() as $attr) {
+ # FIXME: xmlns, nsuri?
+ if ($attr->name() == 'id') {
+ $id = $attr->value();
+ if ($clean) {
+ $child->remove_attribute($attr->name());
+ }
+ }
+ }
+ }
+
+ # check all substitutions to see if we found anything
+ # appropriate
+ foreach (array_keys($obj) as $key) {
+ # FIXME: we would want something like \Q and \E here...
+ if (preg_match('/^' . $tag . '\.(.*)$/', $key, $matches) ||
+ ($id != null && preg_match('/^#' . $id . '\.(.*)$/', $key, $matches))) {
+ $child->set_attribute($matches[0], $obj[$key]);
+ }
+
+ if ($processed) {
+ continue;
+ }
+ if ($key == $tag || ($id != null && $key == ('#'.$id))) {
+ XML_Template_process($child, $obj[$key], $clean, $nsup);
+ $processed = true;
+ }
+ }
+ }
+
+ if (!$processed) {
+ XML_Template_process($child, $obj, $clean, $nsup);
+ }
+ }
+ }
+
+ # FIXME: repeat
+ # FIXME: clean
+}
+
+function is_associative_array($arr)
+{
+ if (!is_array($arr)) {
+ return false;
+ }
+ $diff = array_diff(range(0, count($arr) - 1), array_keys($arr));
+ return (count($diff) > 0);
+}
+?>