04-11-2011

PHP Write post data to XML

Here's a short script that will receive data from a form and turn it into an xml file, translating the posted key value pairs to xml nodes with textnodes.

<?php 
 
$dh = new DataHandler();
$dh->setData($_POST)->save();
 
class  Filewriter{
	private $filename = '';
	private $datadir = ''; 
	private $datasubdir = array('bla','blabla'); 
 
	function __construct($subdir = 0){
		$this->filename =   time() . '-' . uniqid (); 
		$this->datadir = dirname(__FILE__).'/data/' . $this->datasubdir[$subdir]. '/';
	}
 
	function write($data = array()){
		$doc = new DOMDocument();
 
		$doc->formatOutput = true;
		$root = $doc->createElement('result');
		$root = $doc->appendChild($root);
 
		foreach($data as $key=>$value){
			$tmp = $doc->createElement($key);
			$text = $doc->createTextNode($value);
			$text = $tmp->appendChild($text);
			$root->appendChild($tmp);
		}
 
		$doc->save($this->datadir.$this->filename.'.xml'); 
	}
}
 
class DataHandler {
	private $filewriter;
	private $data;
	function __construct(){
		$this->filewriter = new Filewriter();
	}
	function setData($data){
		$this->data = $data;
		return $this; 
	}
 
	function save(){
		if (count($this->data)){
			$this->filewriter->write($this->data);
		}
 
	}
}

Comments:

Your comment:

»

 

[x]