Monday, October 21, 2013

php super xml writer from array objects with attr, cdata

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * b.boldbaatar
 *
 * xml tool for array to xml
 * @author        HiimelOyun Dev Team
 * @link        boroo_c@yahoo.com
 */
// ------------------------------------------------------------------------

class HO_XmlTool {

    protected static $FOLDER = 'xml/';

    public function __construct() {
      
    }

    // read
    // -----------------------------------------------------------------------
    public function read_file($file_name) {
        $file_path = FILESPATH . self::$FOLDER . trim($file_name, '/');
        $reader = new XMLReader();

        if (!$reader->open(site_url($file_path))) {
            die("Failed to open 'data.xml'");
        }
        $output = '';
        if ($reader->read()) {
            $output = $reader->readOuterXml();
        }
        $reader->close();
        return $output;
    }

    public function load_file($file_name) {
        $file_path = FILESPATH . self::$FOLDER . trim($file_name, '/');
        $reader = new XMLReader();

        if (!$reader->open(site_url($file_path))) {
            die("Failed to open 'data.xml'");
        }
        $node = NULL;
        while ($reader->read()) {
            $node = $reader->expand();
            if ($node->nodeType == XMLReader::ELEMENT) {
                break;
            }
        }
        $reader->close();
        return $node;
    }

    public function load_xml($xml) {
        $reader = new XMLReader();

        if (!$reader->xml($xml)) {
            die("Failed to open 'data.xml'");
        }
        $node = NULL;
        while ($reader->read()) {
            $node = $reader->expand();
            if ($node->nodeType == XMLReader::ELEMENT) {
                break;
            }
        }
        $reader->close();
        return $node;
    }

    // write
    // -----------------------------------------------------------------------

    public function &start($prm_xsltFilePath = '') {
        $xml_writer = new XMLWriter();
        $xml_writer->openMemory();
        $xml_writer->setIndent(true);
        $xml_writer->setIndentString(' ');
        $xml_writer->startDocument('1.0', 'UTF-8');
        if ($prm_xsltFilePath) {
            $this->writePi('xml-stylesheet', 'type="text/xsl" href="' . $prm_xsltFilePath . '"');
        }
        return $xml_writer;
    }

    public function end(&$xml_writer) {
        $xml_writer->endDocument();
        return $xml_writer->outputMemory();
    }

    public function fromArray($prm_array, &$xml_writer) {
        foreach ($prm_array as $index => $element) {
            if (is_array($element)) {
                if (!is_int($index)) {
                    $this->_startElement($xml_writer, $index, $element);
                    $this->_endElement($xml_writer);
                } else {
                    $this->fromArray($element, $xml_writer);
                }
            } else {
                $this->_startElement($xml_writer, $index, $element);
                $this->_endElement($xml_writer);
            }
        }
    }

    private function _startElement(&$xml_writer, $name, $value) {
        $cdata = false;
        $attrs = array();
        $index = json_decode($name);

        if (is_array($index) && !empty($index)) {
            $list = (array) $index;

            foreach ($list as $item) {
                if (is_bool($item)) {
                    $cdata = $item;
                } elseif (is_object($item)) {
                    $attrs = (array) $item;
                } else {
                    $name = $item;
                }
            }
        }
      
        $xml_writer->startElement($name);
        if (count($attrs) > 0) {
            foreach ($attrs as $attr_name => $attr_value) {
                $xml_writer->writeAttribute($attr_name, $attr_value);
            }
        }
        if (!is_array($value)) {
            if ($cdata) {
                $xml_writer->writeCData($value);
            } else {
                if (!is_null($value)) {
                    $xml_writer->text($value);
                }
            }
        } else {
            $this->fromArray($value, $xml_writer);
        }
    }

    private function _endElement(&$xml_writer) {
        $xml_writer->endElement();
    }

}

?>

usage

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class some extends HO_Site {

    public function index() {
        $this->load->library('XmlTool');
        $val = json_encode(array('name', array('role' => 'admin'), TRUE));
        $prm_array = array(
            'class' => array(
                //'["name",{"role":"admin"},true]'
                $val => 'computer software',
                'employees' => array(
                    array(
                        'employee' => array(
                            'name' => 'boroo',
                            'tasks' => array(
                                array(
                                    'task' => array(
                                        'name' => 'com1'
                                    )
                                ),
                                array(
                                    'task' => array(
                                        'name' => 'com2',
                                        'time' => '3'
                                    )
                                ),
                            )
                        )
                    ),
                    array(
                        'employee' => array(
                            'name' => 'odgii',
                        )
                    )
                )
            )
        );

        $xml = new HO_XmlTool();
        $xml_writer = $xml->start();
        $xml->fromArray($prm_array, $xml_writer);
        header('Content-type: text/xml');
        echo $xml->end($xml_writer);
    }

}

?>

No comments: