软讯网络 > 网站建设 > PHP > xml2array 完美实现
【标 题】:xml2array 完美实现
【关键字】:
xml2array
【来 源】:http://www.cublog.cn/u/15199/showart.php?id=153725
xml2array 完美实现
本来php手册中有simplexml2array的原型,可是我发现他有BUG,
也曾发帖提问过,没有引起大家的注意。就自己重新写了一个
<?php
/*****
功能:本来php手册中有simplexml2array的原型,可是我发现他有BUG,
也曾发帖提问过,没有引起大家的注意。就自己重新写了一个
作者:achun achun.shx@gamil.com
版权:BSD
日期:2006-8-10
**/
//这是原来的
function simplexml2array($xml) {
if (get_class($xml) == 'SimpleXMLElement') {
$attributes = $xml->attributes();
foreach($attributes as $k=>$v) {
if ($v) $a[$k] = (string) $v;
}
$x = $xml;
$xml = get_object_vars($xml);
}
if (is_array($xml)) {
if (count($xml) == 0) return (string) $x; // for CDATA
foreach($xml as $key=>$value) {
$r[$key] = simplexml2array($value);
}
if (isset($a)) $r['@'] = $a; // Attributes
return $r;
}
return (string) $xml;
}
//这是我写的
function simplexml4array($xmle){
$haschildren=false;
foreach($xmle->children() as $k=>$c)
{
$haschildren=true;
$r[$k]=simplexml4array($c);
}
foreach($xmle->attributes() as $k=>$c)
{
$r['@'][$k]=(string)$c;
}
if(!$haschildren)
{
$r['innerText']=(string)$xmle;
}
return $r;
}
//附上一个测试的例子
$str=<<<XML
<?xml version="1.0" ?>
<library>
<book>
<ddd id="x6" dd="xx">swwss</ddd>
<ddd id="y7" dd='yy'>
<dd>ccc</dd>
</ddd>
</book>
</library>
XML;
$xml = simplexml_load_string($str);
print_r(simplexml2array($xml));
print_r(simplexml4array($xml));
?>
【相关文章】
没有相关文章