PHP數組與XML之間的轉換的例子

來源:互聯網
上載者:User

PHP將數群組轉換成XML

PHP可以將數群組轉換成xml格式,簡單的辦法是遍曆數組,然後將數組的key/value轉換成xml節點,再直接echo輸出了,如:

 代碼如下 複製代碼

function arrayToXml($arr){
    $xml = "<root>";
    foreach ($arr as $key=>$val){
        if(is_array($val)){
            $xml.="<".$key.">".arrayToXml($val)."</".$key.">";
        }else{
            $xml.="<".$key.">".$val."</".$key.">";
        }
    }
    $xml.="</root>";
    return $xml;
}

我測試了下,這個最簡單,速度又快,支援多為數組,中文也不會亂碼。

另一種方法是利用DOMDocument來產生xml結構:

 代碼如下 複製代碼

function arrayToXml($arr,$dom=0,$item=0){
    if (!$dom){
        $dom = new DOMDocument("1.0");
    }
    if(!$item){
        $item = $dom->createElement("root"); 
        $dom->appendChild($item);
    }
    foreach ($arr as $key=>$val){
        $itemx = $dom->createElement(is_string($key)?$key:"item");
        $item->appendChild($itemx);
        if (!is_array($val)){
            $text = $dom->createTextNode($val);
            $itemx->appendChild($text);
            
        }else {
            arrayToXml($val,$dom,$itemx);
        }
    }
    return $dom->saveXML();
}

它同樣可以將數群組轉換成xml,而且支援多維陣列,產生的xml中文也不會亂碼。

PHP將XML轉換成數組

做介面開發的時候經常會碰到別人提交給你的是xml格式的資料,常見的微信介面、支付寶介面等,他們的介面如發送訊息通訊都是xml格式的,那麼我們先想辦法拿到這個xml資料,然後再將其轉化成數組。
假設我們擷取到一個這樣的XML:

 代碼如下 複製代碼

<root>
<user>月光光abcd</user>
<pvs>13002</pvs>
<ips>
<baidu_ip>1200</baidu_ip>
<google_ip>1829</google_ip>
</ips>
<date>2016-06-01</date>
</root>

通過simplexml_load_string()解析讀取xml資料,然後先轉成json格式,再轉換成數組。

 代碼如下 複製代碼
function xmlToArray($xml){    
    //禁止引用外部xml實體
    libxml_disable_entity_loader(true);
    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    $val = json_decode(json_encode($xmlstring),true);  
    return $val;
}

得到數組後,我們就可以對資料進行各種處理了。

下面是網上的

 代碼如下 複製代碼

class ArrayToXML
{
    /**
     * The main function for converting to an XML document.
     * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
     *
     * @param array $data
     * @param string $rootNodeName - what you want the root node to be - defaultsto data.
     * @param SimpleXMLElement $xml - should only be used recursively
     * @return string XML
     */
    public static function toXml($data, $rootNodeName = 'data', $xml=null)
    {
        // turn off compatibility mode as simple xml throws a wobbly if you don't.
        if (ini_get('zend.ze1_compatibility_mode') == 1)
        {
            ini_set ('zend.ze1_compatibility_mode', 0);
        }
       
        if ($xml == null)
        {
            $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
        }
       
        // loop through the data passed in.
        foreach($data as $key => $value)
        {
            // no numeric keys in our xml please!
            if (is_numeric($key))
            {
                // make string key...
                $key = "unknownNode_". (string) $key;
            }
           
            // replace anything not alpha numeric
            $key = preg_replace('/[^a-z]/i', '', $key);
           
            // if there is another array found recrusively call this function
            if (is_array($value))
            {
                $node = $xml->addChild($key);
                // recrusive call.
                ArrayToXML::toXml($value, $rootNodeName, $node);
            }
            else
            {
                // add single node.
                                $value = htmlentities($value);
                $xml->addChild($key,$value);
            }
           
        }
        // pass back as string. or simple xml object if you want!
        return $xml->asXML();
    }
}

下面是我自己編輯的代碼

 代碼如下 複製代碼

function arrtoxml($arr,$dom=0,$item=0){
    if (!$dom){
        $dom = new DOMDocument("1.0");
    }
    if(!$item){
        $item = $dom->createElement("root");
        $dom->appendChild($item);
    }
    foreach ($arr as $key=>$val){
        $itemx = $dom->createElement(is_string($key)?$key:"item");
        $item->appendChild($itemx);
        if (!is_array($val)){
            $text = $dom->createTextNode($val);
            $itemx->appendChild($text);
           
        }else {
            arrtoxml($val,$dom,$itemx);
        }
    }
    return $dom->saveXML();
}

XML轉成數組

 代碼如下 複製代碼

如果你使用 curl 擷取的 xml data
$xml = simplexml_load_string($data);
$data['tk'] = json_decode(json_encode($xml),TRUE);
如果是直接擷取 URL 資料的話
$xml = simplexml_load_file($data);
$data['tk'] = json_decode(json_encode($xml),TRUE);
先把 simplexml 對象轉換成 json,再將 json 轉換成數組。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.