RSS

[PHP] Convertir un XML a un Array de datos con Php

Jue, Jul 24, 2008

Open Source, Php, Programacion, Recursos

Antes de empezar este post dejenme les comento, como nota muy importante, que yo no hice este script, si no que lo encontre en la web y se me hizo interesante postearlo aqui lo hizo MA Razzaque Rupom , ya que funciona bastante bien y si algun dia tienen que hacer un parseador y no disponen de tiempo, y desean algo que funcione bien, pues para eso esta este script.

Resulta pues que yo estaba revisando algo que hice pero como que no me habia gustado mucho, y asi que me dedique a buscar alternativas que ya estuvieran hechas, para no reinventar la rueda.

Lo que buscaba era un parser de XML a PHP, pero que jalaran muy bien, entonces di con el siguiente codigo.

class.xmltoarray.php

PHP:
  1. <?
  2. /**
  3. * XMLToArray Generator Class
  4. * @author  :  MA Razzaque Rupom <rupom_315@yahoo.com>, <rupom .bd@gmail.com>
  5. *             Moderator, phpResource (LINK1http://groups.yahoo.com/group/phpresource/LINK1)
  6. *             URL: LINK2http://www.rupom.infoLINK2
  7. * @version :  1.0
  8. * @date       06/05/2006
  9. * Purpose  : Creating Hierarchical Array from XML Data
  10. * Released : Under GPL
  11. */
  12.  
  13. class XmlToArray
  14. {
  15.    
  16.     var $xml='';
  17.    
  18.     /**
  19.     * Default Constructor
  20.     * @param $xml = xml data
  21.     * @return none
  22.     */
  23.    
  24.     function XmlToArray($xml)
  25.     {
  26.        $this->xml = $xml;   
  27.     }
  28.    
  29.     /**
  30.     * _struct_to_array($values, &$i)
  31.     *
  32.     * This is adds the contents of the return xml into the array for easier processing.
  33.     * Recursive, Static
  34.     *
  35.     * @access    private
  36.     * @param    array  $values this is the xml data in an array
  37.     * @param    int    $i  this is the current location in the array
  38.     * @return    Array
  39.     */
  40.    
  41.     function _struct_to_array($values, &$i)
  42.     {
  43.         $child = array();
  44.         if (isset($values[$i]['value'])) array_push($child, $values[$i]['value']);
  45.        
  46.         while ($i++ <count($values)) {
  47.             switch ($values[$i]['type']) {
  48.                 case 'cdata':
  49.                 array_push($child, $values[$i]['value']);
  50.                 break;
  51.                
  52.                 case 'complete':
  53.                     $name = $values[$i]['tag'];
  54.                     if(!empty($name)){
  55.                     $child[$name]= ($values[$i]['value'])?($values[$i]['value']):'';
  56.                     if(isset($values[$i]['attributes'])) {                   
  57.                         $child[$name] = $values[$i]['attributes'];
  58.                     }
  59.                 }   
  60.               break;
  61.                
  62.                 case 'open':
  63.                     $name = $values[$i]['tag'];
  64.                     $size = isset($child[$name]) ? sizeof($child[$name]) : 0;
  65.                     $child[$name][$size] = $this->_struct_to_array($values, $i);
  66.                 break;
  67.                
  68.                 case 'close':
  69.                 return $child;
  70.                 break;
  71.             }
  72.         }
  73.         return $child;
  74.     }//_struct_to_array
  75.    
  76.     /**
  77.     * createArray($data)
  78.     *
  79.     * This is adds the contents of the return xml into the array for easier processing.
  80.     *
  81.     * @access    public
  82.     * @param    string    $data this is the string of the xml data
  83.     * @return    Array
  84.     */
  85.     function createArray()
  86.     {
  87.         $xml    = $this->xml;
  88.         $values = array();
  89.         $index  = array();
  90.         $array  = array();
  91.         $parser = xml_parser_create();
  92.         xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  93.         xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  94.         xml_parse_into_struct($parser, $xml, $values, $index);
  95.         xml_parser_free($parser);
  96.         $i = 0;
  97.         $name = $values[$i]['tag'];
  98.         $array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
  99.         $array[$name] = $this->_struct_to_array($values, $i);
  100.         return $array;
  101.     }//createArray
  102.    
  103.    
  104. }//XmlToArray
  105. ?>

Para usarlo lo haremos de la siguiente forma,

PHP:
  1. <?php
  2. /**
  3. * XMLToArray Generator Class
  4. * @author  :  MA Razzaque Rupom <rupom_315@yahoo.com>, </rupom><rupom .bd@gmail.com>
  5. *             Moderator, phpResource (http://groups.yahoo.com/group/phpresource/)
  6. *             URL: http://www.rupom.info
  7. * @version :  1.0
  8. * @date       06/05/2006
  9. * Purpose  : Creating Hierarchical Array from XML Data
  10. * Released : Under GPL
  11. */
  12.  
  13. require_once "class.xmltoarray.php";
  14.  
  15. //XML Data
  16. $xml_data = "
  17. <result>
  18.    <studentname>
  19.       MA Razzaque
  20.    </studentname>
  21.    <institute>
  22.       RUET
  23.    </institute>
  24.    <dept>
  25.       CSE
  26.    </dept>
  27.    <roll>
  28.       99315
  29.    </roll>
  30.    <class>
  31.       First
  32.    </class>
  33. </result>";
  34.  
  35. //Creating Instance of the Class
  36. $xmlObj    = new XmlToArray($xml_data);
  37. //Creating Array
  38. $arrayData = $xmlObj->createArray();
  39.  
  40. //Displaying the Array
  41. echo "<pre>";
  42. print_r($arrayData);
  43. echo "</pre>";
  44. ?>

Creo que no hay mucho mas que agregar si desean usenlo, recuerden que usa licencia GPL.

[actualizado] gracias Seraphin [/actualizado]
Vía | XML To Array

, , , , ,

This post was written by:

Ajaxman - who has written 576 posts on Ajaxman.


Contact the author

3 Comments For This Post

  1. gafeman Says:

    buenas ajaxman !

    en php5 existe la clase SimpleXMLElement:
    http://es2.php.net/simplexml

    eso es mano de santo hoyga !

  2. Ajaxman Says:

    @gafeman:

    Gracias, ahora que lo mencionas ya antes usaba eso, el simpleXMLElement, en mi ex-trabajo, no se porque no me acorde inclusive hay un post en este blog sobre eso.

    Talvez no lo recorde, pero bueno es otra opcion, la cual por cierto esta muy bien formada.

    saludos y gracias por la visita

  3. Seraphinux Says:

    Saludos chabs... oye solo un detalle, en el codigo de tu clase xmltoarray como que hay algunos caracteres que no lucen bien... igual y es cosa de mi navegador :D (no, no creo)

    Si efectivamente es es solo en el primer codigo.

Leave a Reply