php xml与数组相互转化

xmlConstruct.class.php
<?php
class xmlConstruct extends XMLWriter
{

    /**
     * Constructor.
     * @param string $prm_rootElementName A root element's name of a current xml document
     * @param string $prm_xsltFilePath Path of a XSLT file.
     * @access public
     * @param null
     */
    public function __construct(){

        
    }

    public function setOpenUri($uri)
    {
        $this->openUri($uri);
        $this->setIndent(true);
        $this->setIndentString(' ');
        $this->startDocument('1.0', 'UTF-8');
        $this->startElement('root');
    }

    /**
     * Set an element with a text to a current xml document.
     * @access public
     * @param string $prm_elementName An element's name
     * @param string $prm_ElementText An element's text
     * @return null
     */
    public function setElement($prm_elementName, $prm_ElementText){
        @$this->startElement($prm_elementName);
        $this->text($prm_ElementText);
        $this->endElement();
    }

    /**
     * Construct elements and texts from an array.
     * The array should contain an attribute's name in index part
     * and a attribute's text in value part.
     * @access public
     * @param array $prm_array Contains attributes and texts
     * @return null
     */
    public function fromArray($prm_array){
      if(is_array($prm_array)){


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


      }
    }

    /**
     * Return the content of a current xml document.
     * @access public
     * @param null
     * @return string Xml document
     */
    public function getDocument(){
        $this->endElement();
        $this->endDocument();
        return $this->outputMemory();
    }

    /**
     * Output the content of a current xml document.
     * @access public
     * @param null
     */
    public function output(){
          //header('Content-type: text/xml');
          echo $this->getDocument();
    }
  

}


//$XmlConstruct = new XmlConstruct('root');
//$XmlConstruct->fromArray($contents);
//$XmlConstruct->output();
?>

myXmlReader.class.php
<?php



/*
* @access        public 
* @version        $Revision: 1.1 $ 

* @homepage        http://www.sofee.cn 
* @copyright    Copyright (c) 2004-2005 Sofee Development Team.(http://www.sofee.cn) 
* @since        2005-05-30 
* @see            PEAR:XML_Parser | SimpleXML extension 
*/ 
class myXmlReader { 
     
    /** 
    * XML parser handle 
    * 
    * @var        resource 
    * @see        xml_parser_create() 
    */ 
    var $parser; 

    /** 
    * source encoding 
    * 
    * @var        string 
    */ 
    var $srcenc; 

    /** 
    * target encoding 
    * 
    * @var        string 
    */ 
    var $dstenc; 

    /** 
    * the original struct 
    * 
    * @access    private 
    * @var        array 
    */ 
    var $_struct = array(); 

    /** 
    * Constructor 
    * 
    * @access        public 
    * @param        mixed        [$srcenc] source encoding 
    * @param        mixed        [$dstenc] target encoding 
    * @return        void 
    * @since         
    */ 
    function myXmlReader($srcenc = null, $dstenc = null) { 
        $this->srcenc = $srcenc; 
        $this->dstenc = $dstenc; 
         
        // initialize the variable. 
        $this->parser = null; 
        $this->_struct = array(); 
    } 

    /** 
    * Free the resources 
    * 
    * @access        public 
    * @return        void 
    **/ 
    function free() { 
        if (isset($this->parser) && is_resource($this->parser)) { 
            xml_parser_free($this->parser); 
            unset($this->parser); 
        } 
    } 

    /** 
    * Parses the XML file 
    * 
    * @access        public 
    * @param        string        [$file] the XML file name 
    * @return        void 
    * @since         
    */ 
    function parseFile($file) { 
        $data = @file_get_contents($file) or die("Can't open file $file for reading!"); 
        $this->parseString($data); 
    } 

    /** 
    * Parses a string. 
    * 
    * @access        public 
    * @param        string        [$data] XML data 
    * @return        void 
    */ 
    function parseString($data) { 
        if ($this->srcenc === null) { 
            $this->parser = @xml_parser_create() or die('Unable to create XML parser resource.'); 
        } else { 
            $this->parser = @xml_parser_create($this->srcenc) or die('Unable to create XML parser resource with '. $this->srcenc .' encoding.'); 
        } 
         
        if ($this->dstenc !== null) { 
            @xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->dstenc) or die('Invalid target encoding'); 
        } 
        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);    // lowercase tags 
        xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);        // skip empty tags 
        if (!xml_parse_into_struct($this->parser, $data,$this->_struct)) { 
            printf("XML error: %s at line %d",  
                    xml_error_string(xml_get_error_code($this->parser)),  
                    xml_get_current_line_number($this->parser) 
            ); 
            $this->free(); 
            exit(); 
        } 
         
        $this->_count = count($this->_struct); 
        $this->free(); 
    } 

    /** 
    * return the data struction 
    * 
    * @access        public 
    * @return        array 
    */ 
    function getTree() { 
        $i = 0; 
        $tree = array(); 

        $tree = $this->addNode( 
            $tree,  
            $this->_struct[$i]['tag'],  
            (isset($this->_struct[$i]['value'])) ? $this->_struct[$i]['value'] : '',  
            (isset($this->_struct[$i]['attributes'])) ? $this->_struct[$i]['attributes'] : '',  
            $this->getChild($i) 
        ); 

        unset($this->_struct); 
        return ($tree); 
    } 

    /** 
    * recursion the children node data 
    * 
    * @access        public 
    * @param        integer        [$i] the last struct index 
    * @return        array 
    */ 
    function getChild(&$i) { 
        // contain node data 
        $children = array(); 

        // loop 
        while (++$i < $this->_count) { 
            // node tag name 
            $tagname = $this->_struct[$i]['tag']; 
            $value = isset($this->_struct[$i]['value']) ? $this->_struct[$i]['value'] : ''; 
            $attributes = isset($this->_struct[$i]['attributes']) ? $this->_struct[$i]['attributes'] : ''; 

            switch ($this->_struct[$i]['type']) { 
                case 'open': 
                    // node has more children 
                    $child = $this->getChild($i); 
                    // append the children data to the current node 
                    $children = $this->addNode($children, $tagname, $value, $attributes, $child); 
                    break; 
                case 'complete': 
                    // at end of current branch 
                    $children = $this->addNode($children, $tagname, $value, $attributes); 
                    break; 
                case 'cdata': 
                    // node has CDATA after one of it's children 
                    $children['value'] .= $value; 
                    break; 
                case 'close': 
                    // end of node, return collected data  
                    return $children; 
                    break; 
            } 
         
        } 
        //return $children; 
    } 

    /** 
    * Appends some values to an array 
    * 
    * @access        public 
    * @param        array        [$target] 
    * @param        string        [$key] 
    * @param        string        [$value] 
    * @param        array        [$attributes] 
    * @param        array        [$inner] the children 
    * @return        void 
    * @since         
    */ 
    function addNode($target, $key, $value = '', $attributes = '', $child = '') { 
        if (!isset($target[$key]['value']) && !isset($target[$key][0])) { 
            if ($child != '') { 
                $target[$key] = $child; 
            } 
            if ($attributes != '') { 
                foreach ($attributes as $k => $v) { 
                    $target[$key][$k] = $v; 
                } 
            } 
             
            $target[$key]['value'] = $value; 
        } else { 
            if (!isset($target[$key][0])) { 
                // is string or other 
                $oldvalue = $target[$key]; 
                $target[$key] = array(); 
                $target[$key][0] = $oldvalue; 
                $index = 1; 
            } else { 
                // is array 
                $index = count($target[$key]); 
            } 

            if ($child != '') { 
                $target[$key][$index] = $child; 
            } 

            if ($attributes != '') { 
                foreach ($attributes as $k => $v) { 
                    $target[$key][$index][$k] = $v; 
                } 
            } 
            $target[$key][$index]['value'] = $value; 
        } 
        return $target; 
    } 

}

demo

<?php
require 'myXmlReader.class.php'; 
require 'xmlConstruct.class.php';
   $xml=new xmlConstruct(); 
  $xml->setOpenUri(time().'.xml');         
  $content['info']= array('username'=>'test1','uid'=>'test2','name'=>array('tttt'=>'wwww1','www2'=>'sfgsd')) ;
  $xml->fromArray($content);
 // $xml->output();
 $xml_=new myXmlReader();
 $xml_->parseFile('1408355059.xml');
 $tree = $xml_->getTree();
 //print_r($tree);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值