class XmlUtils
{
public static function xmlStr2Array($str)
{
$sxe = new SimpleXMLElement($str);
return self::xml2Array($sxe);
}
private static function xml2Array($sxe)
{
$arr = array();
if($sxe instanceof SimpleXMLElement) {
$name = $sxe->getName();
if(!empty($name)) {
$arr[$name] = array();
$attrs = $sxe->attributes();
foreach($attrs as $key => $value) {
if(!empty($key)) {
$arr[$name]['attr_'.$key] = (string)$value;
}
}
$children = $sxe->children();
if(is_null($children) || count($children) == 0) {
//echo '<br>' . trim((string)($sxe->asXML())) . '<br>';
// if(0 == count($attrs)) {
// $arr[$name] = trim((string)($sxe->asXML()));
// } else {
$arr[$name]['value'] = trim((string)($sxe->asXML()));
// }
} else {
foreach($children as $child) {
$childName = $child->getName();
if(!empty($childName)) {
$childArr = $this->xml2Array($child);
$key = $childName;
$i = 1;
while(array_key_exists($key, $arr[$name])) {
$key = $childName . $i;
}
$arr[$name][$key] = $childArr[$childName];
}
}
}
}
}
return $arr;
}
}
$result = XmlUtils::xmlStr2Array($result);
?>
{
public static function xmlStr2Array($str)
{
$sxe = new SimpleXMLElement($str);
return self::xml2Array($sxe);
}
private static function xml2Array($sxe)
{
$arr = array();
if($sxe instanceof SimpleXMLElement) {
$name = $sxe->getName();
if(!empty($name)) {
$arr[$name] = array();
$attrs = $sxe->attributes();
foreach($attrs as $key => $value) {
if(!empty($key)) {
$arr[$name]['attr_'.$key] = (string)$value;
}
}
$children = $sxe->children();
if(is_null($children) || count($children) == 0) {
//echo '<br>' . trim((string)($sxe->asXML())) . '<br>';
// if(0 == count($attrs)) {
// $arr[$name] = trim((string)($sxe->asXML()));
// } else {
$arr[$name]['value'] = trim((string)($sxe->asXML()));
// }
} else {
foreach($children as $child) {
$childName = $child->getName();
if(!empty($childName)) {
$childArr = $this->xml2Array($child);
$key = $childName;
$i = 1;
while(array_key_exists($key, $arr[$name])) {
$key = $childName . $i;
}
$arr[$name][$key] = $childArr[$childName];
}
}
}
}
}
return $arr;
}
}
$result = XmlUtils::xmlStr2Array($result);
?>

本文介绍了一个用于将XML字符串转换为数组的实用函数,详细解释了如何解析XML元素,属性和子节点,并提供了代码实现。适用于XML数据处理和解析场景。
165

被折叠的 条评论
为什么被折叠?



