-
Notifications
You must be signed in to change notification settings - Fork 7.7k
Xml Library
The XML library is an XML parser. It currently has limited features, and is more of a helper library.
[b]Updates:[/b]
2006-11-06:
- Allow better recursion, at the cost of increasing depth of all elements
- Add attributes for all non-bottom depth tags
[b]Features:[/b]
- XML file loading
- XML -> array parsing
- Attribute parsing of all non-bottom tags
- written for PHP5 ([b]not[/b] PHP4 compatible)
[b]Example Usage:[/b]
[code]$this->load->library('xml'); if ($this->xml->load('data/forms/login')) { // Relative to APPPATH, ".xml" appended print_r($this->xml->parse()); } [/code]
[b]Library:[/b]
[code]<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/***
- XML library for CodeIgniter
- author: Woody Gilk
- copyright: (c) 2006
- license: http://creativecommons.org/licenses/by-sa/2.5/
-
file: libraries/Xml.php
*/
class Xml { function Xml () { }
private $document; private $filename;
public function load ($file) { /*** * @public * Load an file for parsing */ $bad = array('|//+|', '|../|'); $good = array('/', ''); $file = APPPATH.preg_replace ($bad, $good, $file).'.xml';
if (! file_exists ($file)) {
return false;
}
$this->document = utf8_encode (file_get_contents ($file));
$this->filename = $file;
return true;
} /* END load */
public function parse () { /*** * @public * Parse an XML document into an array */ $xml = $this->document; if ($xml == '') { return false; }
$doc = new DOMDocument ();
$doc->preserveWhiteSpace = false;
if ($doc->loadXML ($xml)) {
$array = $this->flatten_node ($doc);
if (count ($array) > 0) {
return $array;
}
}
return false;
} /* END parse */
private function flatten_node ($node) { /*** * @private * Helper function to flatten an XML document into an array */
$array = array();
foreach ($node->childNodes as $child) {
if ($child->hasChildNodes ()) {
if ($node->firstChild->nodeName == $node->lastChild->nodeName && $node->childNodes->length > 1) {
$array[$child->nodeName][] = $this->flatten_node ($child);
}
else {
$array[$child->nodeName][] = $this->flatten_node($child);
if ($child->hasAttributes ()) {
$index = count($array[$child->nodeName])-1;
$attrs =& $array[$child->nodeName][$index]['__attrs'];
foreach ($child->attributes as $attribute) {
$attrs[$attribute->name] = $attribute->value;
}
}
}
}
else {
return $child->nodeValue;
}
}
return $array;
} /* END node_to_array */ }
?>[/code]