/**
* Array To XML conversion in PHP
*/
class Array2XML extends DomDocument{
public $nodeName;
private $xpath;
private $root;
private $node_name;
/**
* Constructor
*
* Set up the DOM environment
*
* @param string $root The name of the root node
* @param string $nod_name The name numeric keys are called
*
*/
public function __construct($root = 'tests', $node_name = 'test') {
parent::__construct();
$this->encoding = "ISO-8859-1"; // set the encoding
$this->formatOutput = true; // format the output
$this->node_name = $node_name; // set the node names
$this->root = $this->appendChild($this->createElement( $root )); // create the root element
$this->xpath = new DomXPath($this);
//$this->strictErrorChecking = false;
}
/*
* creates the XML representation of the array
*
* @param array $arr The array to convert
* @aparam string $node The name given to child nodes when recursing
*
*/
public function createNode($arr, $node = null) {
if (is_null($node)) {
$node = $this->root;
}
foreach($arr as $element => $value) {
$element = is_numeric($element) ? $this->node_name : $element;
//$value = preg_replace('/[^a-z]/i', '', $value); // $value = htmlentities($value);
$child = $this->createElement($element, (is_array($value) ? null : $value));
$node->appendChild($child);
if (is_array($value)) {
self::createNode($value, $child);
}
}
}
/*
* Return the generated XML as a string
*
* @return string
*/
public function __toString() {
return $this->saveXML();
}
/*
* Array2XML::query() - perform an XPath query on the XML representation of the array
* @param str $query - query to perform
* @return mixed
*/
public function query($query) {
return $this->xpath->evaluate($query);
}
} // Class ends
// Example Use
try {
$xml = new Array2XML('list');
$xml->createNode( $dataArr );
$dataStr = $xml;
}
catch (Exception $e) {
echo $e->getMessage();
}
Thursday, July 1, 2010
PHP Class for Array to XML Conversion
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment