Friday, September 27, 2013

php codeigniter xml document write example with database select sample

XmlDocument.php

<?php

class XmlDocument extends XMLWriter {

    public function __construct($prm_rootElementName, $prm_xsltFilePath = '') {
        $this->openMemory();
        $this->setIndent(true);
        $this->setIndentString(' ');
        $this->startDocument('1.0', 'UTF-8');

        if ($prm_xsltFilePath) {
            $this->writePi('xml-stylesheet', 'type="text/xsl" href="' . $prm_xsltFilePath . '"');
        }

        $this->startElement($prm_rootElementName);
    }

    public function setElement($prm_elementName, $prm_ElementText) {
        $this->startElement($prm_elementName);
        $this->text($prm_ElementText);
        $this->endElement();
    }

    public function fromArray($prm_array) {
        if (is_array($prm_array)) {
            foreach ($prm_array as $index => $element) {
                if (is_array($element)) {
                    $this->startElement($index);
                    $this->fromArray($element);
                    $this->endElement();
                }
                else
                    $this->setElement($index, $element);
            }
        }
    }

    public function getDocument() {
        $this->endElement();
        $this->endDocument();
        return $this->outputMemory();
    }

    public function output() {
        header('Content-type: text/xml');
        echo $this->getDocument();
    }

}

?>


usage 

require APPPATH . 'libraries/XmlDocument.php';
        $contents = array(
            'title' => 'title boroo',
            'description' => 'Simple XHTML document from XML+XSLT files!',
            'attrs' => array(
                "types" => array(
                    "type1" => "type 1",
                    "type2" => "type 2"
                ),
                "size" => "1024kb"
            ),
        );

        $this->load->database();
        $this->db->select('*');
        $this->db->from('table1');
        $query = $this->db->get();
        $result = $query->result_array();
        if ($query->num_rows() > 0) {
            foreach ($result as $row) {
                list($id, $name, $descr, $created) = array_values($row);
                echo "$id, $created<br>";
            }
        }

        $xml = new XmlDocument('root');
        $xml->fromArray($result);
        $xml->output();

No comments: