forked from bcit-ci/CodeIgniter
-
Notifications
You must be signed in to change notification settings - Fork 0
Xml Library
World Wide Web Server edited this page Jul 4, 2012
·
14 revisions
The XML library is an XML parser. It currently has limited features, and is more of a helper library.
[b]Features:[/b]
- XML file loading
- XML -> array parsing
[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->node_to_array ($doc);
if (count ($array) > 0) {
return $array;
}
}
return false;
} /* END parse */
private function node_to_array ($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->node_to_array ($child);
}
else {
$array[$child->nodeName] = $this->node_to_array($child);
}
}
else {
return $child->nodeValue;
}
}
return $array;
} /* END node_to_array */
}
?> [/code]