PHP:XML与数组互相转换

2012年12月23日 发表评论 阅读评论
/**
 * 把XML转化为数组
 *
 */
function xmlToArray($xml, $recursive = false )
{
	if (!$recursive){
		$array = simplexml_load_string($xml);
	} else  {
		$array = $xml;
	}

	$newArray = array ();
	$array = (array) $array ;
	foreach ($array as $key => $value ) {
		$value = (array) $value ;
		if (isset ($value [0])){
			$newArray [$key] = trim($value [0]) ;
		} else {
			$newArray [$key] = self::xmlToArray($value, true) ;
		}
	}
	return $newArray ;
}

/**
 * 把数据转换为XML格式的数据
 *
 */
function arraytoxml($array, $tag)
{
	function ia2xml($array)
	{
		$xml = '';
		foreach ($array as $key=>$value) {
			if (is_array($value)) {
				$xml.="<$key>".ia2xml($value)."";
			} else {
				$xml.="<$key>".$value."";
			}
		}
		return $xml;
	}

	return simplexml_load_string("<$tag>".ia2xml($array)."");
}

$test['type']='lunch';
$test['time']='12:30';
$test['menu']=array('entree'=>'salad', 'maincourse'=>'steak');

//	header('Content-type:text/xml; charset=utf-8');
//	echo arraytoxml($test,"meal")->asXML();
$string = "


Joe
Jane

I know that's the answer -- but what's the question?

";

//echo $string;
print_r(xmlToArray($string));


转载请注明来自:[MSN Spaces]http://msn.shandian.biz/486.html

  1. 本文目前尚无任何评论.