Home >php教程 >PHP源码 >将数组转换为XML

将数组转换为XML

PHP中文网
PHP中文网Original
2016-05-25 17:14:391060browse

将数组转换为XML

<?php
/****************************************************************
*   @ 2011 OsApi.Net Inc.
*   $author : LBC
*   $email  : pochonlee@gmail.com
*   $Id     : toxml.php 2011/1/21
*****************************************************************/
class A2Xml {
    private $version    = &#39;1.0&#39;;
    private $encoding   = &#39;UTF-8&#39;;
    private $root       = &#39;root&#39;;
    private $xml        = null;

    function __construct() {
        $this->xml = new XmlWriter();
    }
    function toXml($data, $eIsArray=FALSE) {
        if(!$eIsArray) {
            $this->xml->openMemory();
            $this->xml->startDocument($this->version, $this->encoding);
            $this->xml->startElement($this->root);
        }
        foreach($data as $key => $value){

            if(is_array($value)){
                $this->xml->startElement($key);
                $this->toXml($value, TRUE);
                $this->xml->endElement();
                continue;
            }
            $this->xml->writeElement($key, $value);
        }
        if(!$eIsArray) {
            $this->xml->endElement();
            return $this->xml->outputMemory(true);
        }
    }
}
$res = array(
    &#39;hello&#39; => &#39;11212&#39;,
    &#39;world&#39; => &#39;232323&#39;,
    &#39;array&#39; => array(
        &#39;test&#39; => &#39;test&#39;,
        &#39;b&#39;    => array(&#39;c&#39;=>&#39;c&#39;, &#39;d&#39;=>&#39;d&#39;)
    ),
    &#39;a&#39; => &#39;haha&#39;
);
$xml = new A2Xml();
echo $xml->toXml($res);

                       

           

2. [图片] QQ截图未命名.gif将数组转换为XML    

1183.gif


                   

以上就是将数组转换为XML的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:用PHP实现的事件机制Next article:文件格式类