xml和json的相互转换

xml和json的相互转换


class xmljson{
    /**
     * xml to json
     */
    public static function xml_to_json($source,$add='xml') { 
        if(is_file($source)){ //传的是文件,还是xml的string的判断 
            $xml_array=simplexml_load_file($source); 
        }else{ 
            $source = ''.$source.'';
            $xml_array=simplexml_load_string($source); 
        } 
        $json = json_encode($xml_array); //php5,以及以上,如果是更早版本,请查看JSON.php 
        return $json; 
    } 

    public static function json_to_xml($source,$charset='utf8') { 
        if(empty($source)){ 
            return false; 
        } 
        //php5,以及以上,如果是更早版本,请查看JSON.php 
        $array = json_decode($source); 
        $xml =''; 
        $xml .= self::change($array); 
        return $xml; 

    } 


    public static function change($source) { 
        $string=""; 
        foreach($source as $k=>$v){ 
            $string .="<".$k.">"; 
            if(is_array($v) || is_object($v)){ 
                $string .= self::change($v); 
            }else{ 
                $string .=$v; 
            } 
            $string .="<\".$k.">";
        } 
        return $string; 
    } 

}

if($argc <=2) echo "Useage : php xmljson.php xml2json aaa.xml".PHP_EOL;
if($argv[1]=='xml2json') echo xmljson::xml_to_json(file_get_contents($argv[2]));
if($argv[1]=='json2xml') echo xmljson::json_to_xml(file_get_contents($argv[2]));

你可能感兴趣的:(php)