Foros del Web » Programando para Internet » PHP »

[APORTE] xml2array

Estas en el tema de [APORTE] xml2array en el foro de PHP en Foros del Web. Aupa, he estado trabajando un poco de como pasar un XML a un array y al final me ha quedado esto, a ver que os ...
  #1 (permalink)  
Antiguo 29/08/2009, 07:22
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
De acuerdo [APORTE] xml2array

Aupa, he estado trabajando un poco de como pasar un XML a un array y al final me ha quedado esto, a ver que os parece:

xml2array.class.php
Código PHP:
<?php
class xml2array
{
    const 
XML2ARRAY_ATTRIBUTES '__atributtes';
    const 
XML2ARRAY_NODEVALUE '__nodevalue';

    public 
$error;

    private 
$array = array();

    public function 
__construct($dom$charset 'utf-8'$version '1.0')
    {
        
$d $this->loadXML($dom$version$charset);        
        if(!
$this->error)
            
$this->array $this->dom2array($d);            
        unset(
$dom$charset$version$d);
    }

    public function 
getArray()
    {
        if(!
$this->array)
            
$this->error 'E_ARRAY';
        else
            return 
$this->array;
    }

    private function 
loadXML($dom$version$charset)
    {
        
$a = new DOMDocument($version$charset);
        
$a->preserveWhiteSpace false;
        if(@
$a->load($dom))
            return 
$a;
        elseif(@
$a->loadXML($dom))
            return 
$a;
        
$this->error 'E_XML';
    }

    private function 
dom2array($dom$parent = array())
    {      
        if(
is_object($dom->childNodes->item(0)) && $dom->nodeType!==&& ($dom->childNodes->item(0)->nodeType===|| $dom->childNodes->item(0)->nodeType===4))
            
$a $dom->childNodes->item(0)->nodeValue;

        else
        {
            
$i 0;
            
$beforeNode '';
            
$a = array();

            foreach(
$dom->childNodes as $b)
            {   
                
$array = array();
                if(
$b->nodeType!==8)
                {
                    if(
$beforeNode!=$b->nodeName)
                    {
                        
$beforeNode $b->nodeName;
                        
$i 0;                                             
                    }

                    if(
$b->hasAttributes())
                        
$a[$b->nodeName][$i][self::XML2ARRAY_ATTRIBUTES] = self::getAttributes($b);

                    if(
$parent)
                        
$c self::dom2array($b$array[$parent][$b->nodeName]);
                    else
                        
$c self::dom2array($b$array[$b->nodeName] = array());

                    
$a[$b->nodeName][$i][self::XML2ARRAY_NODEVALUE] = $c;                
                }
                
$i++;
            }
            unset(
$dom$parent$b$i$beforeNode$c);
            return 
$a;
        }

        unset(
$dom$parent);
        return 
$a;
    }

    private function 
getAttributes($node)
    {
        
$attr = array();
        foreach(
$node->attributes as $a)
               
$attr[$a->name] = $a->value;
        return 
$attr;
    }
}
Su uso:
Código PHP:
<?php
error_reporting
(E_ALL);
include(
'xml2array.class.php');
$a = new xml2array('example.xml');
if(!
$a->error)
{
    
$b $a->getArray();
    if(!
$a->error)
    {
        echo 
"<pre>";        
        
print_r($b);
        echo 
"</pre>";        
    }
    else
        echo 
$a->error;    
}
else
    echo 
$a->error;    
?>
Ejemplo XML: example.xml
Código xml:
Ver original
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <a id="forosdelweb">
  3.     <b id="usuario" id2="fecha">
  4.         zital
  5.     </b>
  6.     <b>
  7.         hola
  8.     </b>
  9. </a>

Resultado:
Código:
Array
(
    [a] => Array
        (
            [0] => Array
                (
                    [__attributes] => Array
                        (
                            [id] => forosdelweb
                        )

                    [__value] => Array
                        (
                            [b] => Array
                                (
                                    [0] => Array
                                        (
                                            [__attributes] => Array
                                                (
                                                    [id] => usuario
                                                    [id2] => fecha
                                                )

                                            [__value] => zital
                                        )

                                    [1] => Array
                                        (
                                            [__value] => hola
                                        )

                                )

                        )

                )

        )

)
Como entrada se puede poner el nombre del fichero XML o incluso un XML dentro de una variable :)
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan

Última edición por ZiTAL; 04/12/2009 a las 08:53 Razón: soporta comentarios en el xml
  #2 (permalink)  
Antiguo 04/12/2009, 08:02
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
Respuesta: [APORTE] xml2array

aupa, he editado la funcion dom2array, ahora soporta comentarios en el XML :)
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 15:31.