Skip to content
World Wide Web Server edited this page Jul 4, 2012 · 14 revisions

Category:Libraries::Other

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');

/***

*/

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 &#40;$file&#41;);
    $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]

Clone this wiki locally