首頁  >  文章  >  後端開發  >  使用php如何將陣列轉換成x​​ml

使用php如何將陣列轉換成x​​ml

王林
王林原創
2021-09-28 17:14:192387瀏覽

使用php將陣列轉換成x​​ml的方法:【class Array_to_Xml{private $version  = '1.0';private $encoding  = 'UTF-8';private $root    = 'ro...】。

使用php如何將陣列轉換成x​​ml

本文操作環境:windows10系統、php 7、thinkpad t480電腦。

下面是使用php將陣列轉換為xml的具體實作程式碼,一起來看吧。

具體實作程式碼:

<?php
class Array_to_Xml
{
    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;
);

header("Content-type:text/xml");//输出xml头信息
$xml = new Array_to_Xml();//实例化类
echo $xml->toXml($res);//转为数组
?>

看下運行的效果:

使用php如何將陣列轉換成x​​ml

#推薦學習:php訓練

以上是使用php如何將陣列轉換成x​​ml的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn