php數組與xml的相互轉化

**
 * 將數組轉換成 XML
 *
 * @param array $data             數組
 * @param array $encoding         編碼(默認是 UTF-8)
 * @param string $rootNodeName    根節點名稱(默認是 data)
 * @param SimpleXMLElement $xml   XML對象(遞歸用)
 * @return string XML
 */
function toXml($data, $encoding = 'UTF-8', $rootNodeName = 'data', $xml = null)
{
    if ($xml == null) {
        $xml = simplexml_load_string('<?xml version="1.0" encoding="'.$encoding.'"?><'.$rootNodeName.' />');
    }

    foreach($data as $key => $value) {
        if (is_numeric($key)) {
            $key = 'item';
        }
        $key = preg_replace('/\W+/i', '', $key);

        if (is_array($value)) {
            $node = $xml->addChild($key);
            toXml($value, $encoding, $rootNodeName, $node);
        } else {
            //$value = htmlentities($value);
            $xml->addChild($key, $value);
        }
    }
    return $xml->asXML();
}
function xml_to_array($xml){
    $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
    if(preg_match_all($reg, $xml, $matches)){
        $count = count($matches[0]);
        for($i = 0; $i < $count; $i++){
            $subxml= $matches[2][$i];
            $key = $matches[1][$i];
            if(preg_match( $reg, $subxml )){
                $arr[$key] = xml_to_array( $subxml );
            }else{
                $arr[$key] = $subxml;
            }
        }
    }
    return $arr;
}
發佈了28 篇原創文章 · 獲贊 17 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章