Maison > php教程 > php手册 > le corps du texte

php中SimpleXMLElement 对象转换为数组

WBOY
Libérer: 2016-05-25 16:42:07
original
1038 Les gens l'ont consulté

PHP 提供了 simplexml_load_string 方法用来解析 XML 格式的字符串,并返回 SimpleXMLElement 对象,不过一般数组是更为适用的,所以也会有转换为普通数组的需求,这个方法测试完全奏效,支持 SimpleXMLElement 对象多层嵌套的情况.

提供两个参数,第一个参数为 SimpleXMLElement 对象,第二个参数为布尔值,控制最终返回值是否包含根节点,代码如下:

<?php
function xmlToArr($xml, $root = true) {
    if (!$xml->children()) {
        return (string)$xml;
    }
    $array = array();
    foreach ($xml->children() as $element => $node) {
        $totalElement = count($xml->{$element});
        if (!isset($array[$element])) {
            $array[$element] = "";
        }
        // Has attributes
        if ($attributes = $node->attributes()) {
            $data = array(
                &#39;attributes&#39; => array() ,
                &#39;value&#39; => (count($node) > 0) ? $this->__xmlToArr($node, false) : (string)$node
            );
            foreach ($attributes as $attr => $value) {
                $data[&#39;attributes&#39;][$attr] = (string)$value;
            }
            if ($totalElement > 1) {
                $array[$element][] = $data;
            } else {
                $array[$element] = $data;
            }
            // Just a value
            
        } else {
            if ($totalElement > 1) {
                $array[$element][] = $this->__xmlToArr($node, false);
            } else {
                $array[$element] = $this->__xmlToArr($node, false);
            }
        }
    }
    if ($root) {
        return array(
            $xml->getName() => $array
        );
    } else {
        return $array;
    }
}
?>
Copier après la connexion


文章链接:

随便收藏,请保留本文地址!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Recommandations populaires
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!