Convert XML and arrays

WBOY
Release: 2016-07-29 09:08:19
Original
936 people have browsed it

Two methods recursive conversion array and xml

 $v) {
		if ($v instanceof simplexmlelement||is_array($v)) {
			$sim[$k]=toarray($v);
		}
	}	
	return $sim;
}
$sx=simplexml_load_file('./try.xml');
print_r($sx);
print_r(toarray($sx));
// 看源代码可以看到,网页返回是报错






$arr=array('a'=>'111',
		'b'=>'2222',
		'c'=>array(
			'd'=>'hahaha',
			'e'=>array(
				'what'=>'the x')));

// 数组转xml,新的数组加入到新xml里,,arr to xml
function toxml($arr,$node=null){
	// 创建新xml文件
	if ($node==null) {
	$simxml=new simpleXMLElement ('');
	}else{
		$simxml=$node;
	}
	// 
	foreach ($arr as $k => $v) {
		if (is_array($v)) {
			// addChild(节点名,内容)
			// 如果是数组,就要建节点 把这个数组里的东西放进去--》v是个数组,
			// 大节点名是k,到下一回,把东西放进这个sim-》addchild里
			toxml($v,$simxml->addChild($k));

			//如果数组键是数字,就要自己给他个标签名,因为直接用数字 会出问题
		}else if (is_numeric($k)) {
			$simxml->addChild('item',$v);	

		}else{
			// 不是数组就直接添加子元素 键名-键值
			$simxml->addChild($k,$v);
		}
	}	
	return $simxml->saveXML();
}

header('content-type:text/xml');
echo toxml($arr);

?>
Copy after login

The above has introduced the conversion of XML and arrays, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!