xml和json的相互转换
<?php
class xmljson{
public static function xml_to_json($source,$add='xml') {
if(is_file($source)){
$xml_array=simplexml_load_file($source);
}else{
$source = '<xml>'.$source.'</xml>';
$xml_array=simplexml_load_string($source);
}
$json = json_encode($xml_array);
return $json;
}
public static function json_to_xml($source,$charset='utf8') {
if(empty($source)){
return false;
}
$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]));