联系我们:416326801#qq.com(#改成@)

img1

PHP将XML转换成数组

925 Views 标签: PHP XML

简单的XML
public static function xmlToArray($xml) {
    libxml_disable_entity_loader(true);
    $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    if( is_array($result) ) {
        return $result;
    }
    return array();
}
带名字空间的XML
//xml转array
public static function xmlToArray($xml) {
	if( !$xml || empty($xml) ){
		return array();	
	}
	$dom = new DOMDocument();
	$dom->loadXML($xml);
	return self::getArray($dom->documentElement);
}
	
private static function getArray($node) {
	$array = false;
	if ($node->hasAttributes()) {
		foreach ($node->attributes as $attr) {
			$array[$attr->nodeName] = $attr->nodeValue;
		}
	}
	
	if ($node->hasChildNodes()) {
		if ($node->childNodes->length == 1) {
			$array[$node->firstChild->nodeName] = self::getArray($node->firstChild);
		} else {
			foreach ($node->childNodes as $childNode) {
				if ($childNode->nodeType != XML_TEXT_NODE) {
					$array[$childNode->nodeName][] = self::getArray($childNode);
				}
			}
		}
	} else {
		return $node->nodeValue;
	}
	return $array;
}

如果觉得我的文章对您有用,打赏一下呗.

wxpay.png