xml转json
/**
* 将xml转为json
* @param string $source 文件路径|字符串
*/
function xmlToArray($source) {
if(is_file($source)){ //传的是文件,还是xml的string的判断
$xml_array=simplexml_load_file($source);
}else{
$xml_array=simplexml_load_string($source);
}
return json_encode($xml_array);
}
xml转json
/**
* json转xml文件
* @param string $source json字符串
* @param string $charset 编码
*/
function jsonToXml($source, $charset="UTF-8")
{
if(empty($source))
{
return false;
}
$array = json_decode($source, true);
$xml = "<?xml version=\"1.0\" encoding=\"".$charset."\"?>";
$xml .= json_to_xml_content($array,'xmeml');
$xml .= '</xmeml>';
return $xml;
}
/**
* 递归
* @param array $source 递归内容
* @param string $parent_key 上级标签
*/
function json_to_xml_content( $source, $parent_key )
{
$string = "";
foreach($source as $k=>$v)
{
if( $k == '@attributes' ){
$string .= '<' . $parent_key;
foreach ( $v as $i => $item ){
$string .= ' '.$i.'="'.$item.'"';
}
$string .= '>';
}
else{
$parent_key = $k;
if(is_array($v) || is_object($v))
{
if(is_numeric(array_key_first($v))){
foreach ( $v as $item ){
if(array_key_first($item) != '@attributes'){
$string .= "<".$parent_key.">";
}
$string .= json_to_xml_content($item, $parent_key);
$string .= "</".$parent_key.">";
}
}
elseif (array_key_first($v) == '@attributes'){
$string .= json_to_xml_content($v, $parent_key);
$string .= "</".$k.">";
}
else{
$string .= "<".$k.">";
$string .= json_to_xml_content($v, $parent_key);
$string .= "</".$k.">";
}
}
else {
$string .= "<".$k.">";
$string .= $v;
$string .= "</".$k.">";
}
}
}
return $string;
}