jesse1981
1/9/2014 - 10:38 PM

Useful PHP functions to work with XMLs. libxml library is a required package

Useful PHP functions to work with XMLs. libxml library is a required package

<?php
class xmlreader {
    var $filename;
    var $dataset;
    
    public function __construct($filename) {
        $this->filename = $filename;
        $this->load($this->filename);
    }
    
    // private
    private function load($filename) {
        $handle = fopen($filename,'r');
        $buffer = "";
        if ($handle) {
            $buffer = fread($handle,filesize($filename));
            fclose($handle);
        }
        if ($buffer) { $this->dataset = simplexml_load_string($buffer); return true; }
        else return false;
    }
    
    // public
    public function getAttributes($node) {
        $result = array();
        if ($node) {
            $atts = (array)$node->attributes();
            if (count($atts)) {
                foreach ($atts["@attributes"] as $a=>$b) {
                    $result[$a] = $b;
                }
            }
            return $result;
        }
        else return false;
    }
    public function getChildren($node) {
        if ($node) {
            return $node->children();
        }
        else return false;
    }
    public function getXpath($path) {
        $results = array();
        if ($this->dataset) {
            foreach ($this->xpath($path) as $result) $results[] = $result;
            return $results;
        }
        else return -1;
    }
}
?>