PHP JSON转XML

/ 0评 / 0

PHP JSON转换XML方法。当然方法不止这一种。

class JsonHelper{
    public function json_to_xml($source,$charset='utf8') {
        if(empty($source)){
            return false;
        }
        $array = json_decode($source, false , 512 , JSON_BIGINT_AS_STRING);
        $xml ='<?xml version="1.0" encoding="UTF-8"?><root>';//xml头
        $xml .= $this->change($array);
        $xml .='</root>';
        return $xml;
    }
    public function change($source) {
        $string="";
        foreach($source as $k=>$v){
            if($v == null)continue;
            if(!is_numeric($k)){//判断是否为纯数字
                $string .="<".$k.">";
            }else{
                $string .="<"."list".$k.">";
            }
            if(is_array($v) || is_object($v)){//判断是否为数组或者对象就递归调用
                $string .= $this->change($v);
            }else{
                $string .=htmlspecialchars(($v))."";//取得标签数据
            }
            if(!is_numeric($k)){
                $string .="</".$k.">";
            }else{
                $string .="</"."list".$k.">";
            }
        }
        return $string;
    }
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *