class jsonToXml { public static function convert($data, DOMDocument $dom = null, DOMElement $xml = null) { if(!$dom) { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->formatOutput = true; } if(!$xml) { $xml = $dom->createElement('xml'); $xml->setAttribute('root', 'http://www.ghostwei.com'); //设置一些属性 $dom->appendChild($xml); } foreach($data As $key => $val) { $key = !is_string($key) ? $xml->tagName : $key; if(is_array($val) && count($val) && preg_match('/^[\d]+$/', implode('', array_keys($val)))) { foreach($val As $k => $v) { $e = $dom->createElement($key); $xml->appendChild($e); if(is_object($v) || is_array($v)) { self::convert($v, $dom, $e); continue; } if(is_string($v) && preg_match('/<[^>]+>/', $v)) { $e->appendChild($dom->createCDATASection($v)); } else { $e->nodeValue = htmlspecialchars((string) $v); } } continue; } if((is_object($val) || is_array($val)) && count($val)) { $e = $dom->createElement($key); $xml->appendChild($e); self::convert($val, $dom, $e); continue; } if((is_object($val) || is_array($val)) && !count($val)) { $xml->appendChild($dom->createElement($key)); continue; } $e = $dom->createElement($key); $xml->appendChild($e); if(is_string($val) && preg_match('/<[^>]+>/', $val)) { $e->appendChild($dom->createCDATASection($val)); } else { $e->nodeValue = htmlspecialchars((string) $val); } } return $dom->saveXML(); } }
header('Content-Type:text/xml; charset=utf-8'); echo jsonToXml::convert($json);
stdClass Object ( [com] => ghostwei [nu] => 61693388 [message] => ok [status] => 1 [state] => 1 [data] => Array ( [0] => stdClass Object ( [time] => 2016-11-07 11:40:41 [context] => 包裹已揽收 ) [1] => stdClass Object ( [time] => 2016-11-07 11:46:10 [context] => Parcel Departure Scan ) [2] => stdClass Object ( [time] => 2016-12-13 12:42:49 [context] => 包裹已到达 Markham(ON) 转运中心 ) [3] => stdClass Object ( [time] => 2016-12-13 12:57:24 [context] => 包裹已到达 Markham(ON) 转运中心 ) [4] => stdClass Object ( [time] => 2016-12-13 13:04:08 [context] => 包裹已取消发货,返回收货点,原因:test ) ) )
阅读:913
评论:1
゛. - 看過世间最冷漠滴眼神, 爱過⒈生最无缘滴人﹎
unknown
不错
回复 7年前7月8日 175.0.30.164