Foros del Web » Programando para Internet » PHP »

Problema simpleXML

Estas en el tema de Problema simpleXML en el foro de PHP en Foros del Web. Holas! Estoy intentando analizar un fichero XML y meter los datos en un array (para luego introducirlos en una bbdd) pero no hay manera!!. Alguien ...
  #1 (permalink)  
Antiguo 06/09/2009, 06:44
Avatar de neodani  
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 17 años, 2 meses
Puntos: 20
Recorrer fichero XML, ¿Cuál es el mejor metodo?

Holas!

Estoy intentando analizar un fichero XML y meter los datos en un array (para luego introducirlos en una bbdd) pero no hay manera!!. Alguien me echa una mano con esto??

Fichero XML

Código PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Analizar XML</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php

$xmlstr 
= <<<XML
<?xml version="1.0" encoding="utf-8" ?>
<leaguelist><league name="Liga BBVA" leaguelink="https://adserver.itsfogo.com/click.aspx?zoneid=34296&amp;page=betsnew.aspx&amp;LeagueIDs=16108" >
<event  name="Deportivo - Málaga" eventdate="13.09.09 / 17:00" eventlink="https://adserver.itsfogo.com/click.aspx?zoneid=34296&amp;page=betsnew.aspx&amp;EventID=1671799">
<games name="1 X 2">
<result  name="1" odd="1,85" placebetlink="https://adserver.itsfogo.com/click.aspx?zoneid=34296&amp;ResultIDs=53673778&amp;GameIDs=14764329&amp;ResultOdds=1.85&amp;Stake=10"/>
<result  name="X" odd="3,30" placebetlink="https://adserver.itsfogo.com/click.aspx?zoneid=34296&amp;ResultIDs=53673779&amp;GameIDs=14764329&amp;ResultOdds=3.30&amp;Stake=10"/>
<result  name="2" odd="3,75" placebetlink="https://adserver.itsfogo.com/click.aspx?zoneid=34296&amp;ResultIDs=53673780&amp;GameIDs=14764329&amp;ResultOdds=3.75&amp;Stake=10"/>
</games>
</event>
<event  name="Espanyol - R. Madrid" eventdate="13.09.09 / 17:00" eventlink="https://adserver.itsfogo.com/click.aspx?zoneid=34296&amp;page=betsnew.aspx&amp;EventID=1671800">
<games name="1 X 2">
<result  name="1" odd="5,75" placebetlink="https://adserver.itsfogo.com/click.aspx?zoneid=34296&amp;ResultIDs=53673876&amp;GameIDs=14764346&amp;ResultOdds=5.75&amp;Stake=10"/>
<result  name="X" odd="3,55" placebetlink="https://adserver.itsfogo.com/click.aspx?zoneid=34296&amp;ResultIDs=53673877&amp;GameIDs=14764346&amp;ResultOdds=3.55&amp;Stake=10"/>
<result  name="2" odd="1,55" placebetlink="https://adserver.itsfogo.com/click.aspx?zoneid=34296&amp;ResultIDs=53673878&amp;GameIDs=14764346&amp;ResultOdds=1.55&amp;Stake=10"/>
</games>
</event>
</league></leaguelist>
XML;

$xml simplexml_load_string($xmlstr);

foreach(
$xml->league->attributes() as $a => $b) {
    echo 
$a,'="',$b,"<br/>";
}

foreach (
$xml->league as $league) {
    foreach(
$xml->league->event->attributes() as $a => $b) {
        echo 
$a,'="',$b,"<br/>";
        foreach(
$xml->league->event->games->attributes() as $a => $b) {
            echo 
$a,'="',$b,"<br/>";}
    }
}

?>
</body>
</html>
He seguido los consejo de http://www.php-es.com/ref.simplexml.html pero no hay manera.

Muchas gracias de antemano!

Última edición por neodani; 10/09/2009 a las 13:24
  #2 (permalink)  
Antiguo 06/09/2009, 09:42
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Problema simpleXML

¿y porque dices que no hay manera??

acaso te da error el código ??

osea... el código que tienes si sirve??

para mostrar los datos, claro... pero para insertarlos en un array no es automático !!


esa parte la debes programar tu... o ¿que estabas pensando??
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #3 (permalink)  
Antiguo 06/09/2009, 13:30
Avatar de neodani  
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 17 años, 2 meses
Puntos: 20
Respuesta: Problema simpleXML

Cita:
Iniciado por pateketrueke Ver Mensaje
¿y porque dices que no hay manera??

acaso te da error el código ??

osea... el código que tienes si sirve??

para mostrar los datos, claro... pero para insertarlos en un array no es automático !!


esa parte la debes programar tu... o ¿que estabas pensando??
Soy un negado para meter los datos en un array, porque entiendo que para construir el array como toca se tiene que utilizar un array dentro de otro, no?
  #4 (permalink)  
Antiguo 06/09/2009, 14:39
Avatar de neodani  
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 17 años, 2 meses
Puntos: 20
Respuesta: Problema simpleXML

Intentaré explicarme... quiero conseguir

Un array que tenga la siguiente estructura en bloques, uno metido dentro de otro:

Competiciones = [
Primera Division
Segunda Division
Tercera Division
]

Dentro de Primera Division hay:
Partidos = [
Partido 1
Partido 2
Partido 3
Partido 4
...
]

Y dentro de cada partido encontramos los mercados
Mercado 1X2 = [
1=1.20
X=3.40
2=4.60
]

No sé formarlo... Alguna idea?

Muchas gracias
  #5 (permalink)  
Antiguo 06/09/2009, 15:41
Avatar de neodani  
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 17 años, 2 meses
Puntos: 20
Respuesta: Problema simpleXML

He conseguido mostrar los datos del XML en formato array

Código php:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title>Analizar XML</title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. </head>
  7. <body>
  8. <?php
  9.  
  10.  class xml {
  11.    
  12.     var $matriz = array();
  13.     var $resultado;
  14.     var $informacion;
  15.    
  16.     function xml($contenido) {
  17.    
  18.             $this->resultado = xml_parser_create ();
  19.             xml_set_object($this->resultado,$this);
  20.             xml_set_element_handler($this->resultado, "abrir", "cerrar");
  21.            
  22.             xml_set_character_data_handler($this->resultado, "info");
  23.        
  24.             $this->informacion = xml_parse($this->resultado,$contenido);
  25.                          
  26.             xml_parser_free($this->resultado);
  27.            
  28.             return $this->matriz;
  29.     }
  30.     function abrir($parser, $nombre, $atributos) {
  31.         $etiqueta = array("nombre"=>$nombre,"atributos"=>$atributos);
  32.         array_push($this->matriz,$etiqueta);
  33.     }
  34.    
  35.     function info($parser, $etiqueta_info) {
  36.         if(trim($etiqueta_info)) {
  37.             if(isset($this->matriz[count($this->matriz)-1]['info'])) {
  38.                $this->matriz[count($this->matriz)-1]['info'] .= $etiqueta_info;
  39.             }
  40.             else {
  41.                $this->matriz[count($this->matriz)-1]['info'] = $etiqueta_info;
  42.             }
  43.         }
  44.     }
  45.    
  46.     function cerrar($parser, $nombre) {
  47.        $this->matriz[count($this->matriz)-2]['hijo'][] = $this->matriz[count($this->matriz)-1];
  48.         array_pop($this->matriz);
  49.     }
  50.  }
  51.  
  52. $url = "http://partnerfeed.itsfogo.com/partnerfeed.aspx?partnerfeedID=1305&ZoneID=34296&partnerTargetLink=&partnerField=itsfogoTargetLink";
  53. $xml_contenido = file_get_contents($url,'r');
  54.  
  55. $xml = new xml($xml_contenido);
  56.  
  57. echo '<pre>';
  58. print_r($xml->matriz);
  59. echo '</pre>';
  60.  
  61. ?>
  62.  
  63.  
  64. </body>
  65. </html>

Ahora me falta acceder a cada una de las posiciones y guardar los datos en un base de datos mysql.

¿Alguna sugerencia?

Gracias
  #6 (permalink)  
Antiguo 06/09/2009, 15:55
Avatar de neodani  
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 17 años, 2 meses
Puntos: 20
Respuesta: Problema simpleXML

Si el resultado del array es el siguiente:

No sé como acceder a las posiciones, por ejemplo
[NAME] => Liga BBVA

Código:
Array
(
    [0] => Array
        (
            [nombre] => LEAGUELIST
            [atributos] => Array
                (
                )

            [hijo] => Array
                (
                    [0] => Array
                        (
                            [nombre] => LEAGUE
                            [atributos] => Array
                                (
                                    [NAME] => Liga BBVA
                                    [LEAGUELINK] => https://adserver.itsfogo.com/click.aspx?zoneid=34296&page=betsnew.aspx&LeagueIDs=16108
                                )

                            [hijo] => Array
                                (
                                    [0] => Array
                                        (
                                            [nombre] => EVENT
                                            [atributos] => Array
                                                (
                                                    [NAME] => Deportivo - Málaga
                                                    [EVENTDATE] => 13.09.09 / 17:00
                                                    [EVENTLINK] => https://adserver.itsfogo.com/click.aspx?zoneid=34296&page=betsnew.aspx&EventID=1671799
                                                )

                                            [hijo] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [nombre] => GAMES
                                                            [atributos] => Array
                                                                (
                                                                    [NAME] => 1 X 2
                                                                )

                                                            [hijo] => Array
                                                                (
                                                                    [0] => Array
                                                                        (
                                                                            [nombre] => RESULT
                                                                            [atributos] => Array
                                                                                (
                                                                                    [NAME] => 1
                                                                                    [ODD] => 1,85
                                                                                    [PLACEBETLINK] => https://adserver.itsfogo.com/click.aspx?zoneid=34296&ResultIDs=53673778&GameIDs=14764329&ResultOdds=1.85&Stake=10
                                                                                )

                                                                        )

                                                                    [1] => Array
                                                                        (
                                                                            [nombre] => RESULT
                                                                            [atributos] => Array
                                                                                (
                                                                                    [NAME] => X
                                                                                    [ODD] => 3,30
                                                                                    [PLACEBETLINK] => https://adserver.itsfogo.com/click.aspx?zoneid=34296&ResultIDs=53673779&GameIDs=14764329&ResultOdds=3.30&Stake=10
                                                                                )

                                                                        )

                                                                    [2] => Array
                                                                        (
                                                                            [nombre] => RESULT
                                                                            [atributos] => Array
                                                                                (
                                                                                    [NAME] => 2
                                                                                    [ODD] => 3,75
                                                                                    [PLACEBETLINK] => https://adserver.itsfogo.com/click.aspx?zoneid=34296&ResultIDs=53673780&GameIDs=14764329&ResultOdds=3.75&Stake=10
                                                                                )

                                                                        )

                                                                )

                                                        )

                                                )

                                        )

                                    [1] => Array
                                        (
                                            [nombre] => EVENT
                                            [atributos] => Array
                                                (
                                                    [NAME] => Espanyol - R. Madrid
                                                    [EVENTDATE] => 13.09.09 / 17:00
                                                    [EVENTLINK] => https://adserver.itsfogo.com/click.aspx?zoneid=34296&page=betsnew.aspx&EventID=1671800
                                                )

                                            [hijo] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [nombre] => GAMES
                                                            [atributos] => Array
                                                                (
                                                                    [NAME] => 1 X 2
                                                                )

                                                            [hijo] => Array
                                                                (
                                                                    [0] => Array
                                                                        (
                                                                            [nombre] => RESULT
                                                                            [atributos] => Array
                                                                                (
                                                                                    [NAME] => 1
                                                                                    [ODD] => 5,75
                                                                                    [PLACEBETLINK] => https://adserver.itsfogo.com/click.aspx?zoneid=34296&ResultIDs=53673876&GameIDs=14764346&ResultOdds=5.75&Stake=10
                                                                                )

                                                                        )

                                                                    [1] => Array
                                                                        (
                                                                            [nombre] => RESULT
                                                                            [atributos] => Array
                                                                                (
                                                                                    [NAME] => X
                                                                                    [ODD] => 3,55
                                                                                    [PLACEBETLINK] => https://adserver.itsfogo.com/click.aspx?zoneid=34296&ResultIDs=53673877&GameIDs=14764346&ResultOdds=3.55&Stake=10
                                                                                )

                                                                        )
¿Alguna idea?

Edito: Conseguido xD

$salida[0]['hijo'][0]['atributos']['NAME'];

Última edición por neodani; 06/09/2009 a las 16:01
  #7 (permalink)  
Antiguo 06/09/2009, 16:05
Avatar de neodani  
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 17 años, 2 meses
Puntos: 20
Respuesta: Problema simpleXML

Me falta moverme por los datos, imagino que con varios foreach()

Sin embargo, lo he intentado con

Código PHP:
echo '<pre>';
//print_r($xml->matriz);
$salida = ($xml->matriz);
echo 
'</pre>';

foreach (
$salida as $i) {
    echo 
$salida[0]['hijo'][$i]['atributos']['NAME'];

Pero no lo consigo, ya no se como tratar al objeto!
Warning: Illegal offset type in C:\AppServ\www\00-laboratorio_test\xml\prueba1.php on line 64
  #8 (permalink)  
Antiguo 07/09/2009, 14:51
Avatar de neodani  
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 17 años, 2 meses
Puntos: 20
Respuesta: Problema simpleXML

He conseguido iterarlo a mi manera xDD

¿Me podéis dar vuestra opinión? ¿lo hariáis de otra forma? Al final lo que quiero conseguir es introducir estos datos en una bbdd mysql

Código php:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title>Analizar XML</title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. </head>
  7. <body>
  8. <?php
  9.  
  10. class xml {
  11.  
  12. var $matriz = array();
  13. var $resultado;
  14. var $informacion;
  15.  
  16. function xml($contenido) {
  17.  
  18.         $this->resultado = xml_parser_create ();
  19.         xml_set_object($this->resultado,$this);
  20.         xml_set_element_handler($this->resultado, "abrir", "cerrar");
  21.        
  22.         xml_set_character_data_handler($this->resultado, "info");
  23.    
  24.         $this->informacion = xml_parse($this->resultado,$contenido);
  25.                      
  26.         xml_parser_free($this->resultado);
  27.        
  28.         return $this->matriz;
  29. }
  30. function abrir($parser, $nombre, $atributos) {
  31.     $etiqueta = array("nombre"=>$nombre,"atributos"=>$atributos);
  32.     array_push($this->matriz,$etiqueta);
  33. }
  34.  
  35. function info($parser, $etiqueta_info) {
  36.     if(trim($etiqueta_info)) {
  37.         if(isset($this->matriz[count($this->matriz)-1]['info'])) {
  38.            $this->matriz[count($this->matriz)-1]['info'] .= $etiqueta_info;
  39.         }
  40.         else {
  41.            $this->matriz[count($this->matriz)-1]['info'] = $etiqueta_info;
  42.         }
  43.     }
  44. }
  45.  
  46. function cerrar($parser, $nombre) {
  47.    $this->matriz[count($this->matriz)-2]['hijo'][] = $this->matriz[count($this->matriz)-1];
  48.     array_pop($this->matriz);
  49. }
  50. }
  51.  
  52. // XML origen
  53. $url = "http://partnerfeed.itsfogo.com/partnerfeed.aspx?partnerfeedID=1305&ZoneID=34296&partnerTargetLink=&partnerField=itsfogoTargetLink";
  54. $xml_contenido = file_get_contents($url,'r');
  55.  
  56. $xml = new xml($xml_contenido);
  57.  
  58. echo '<pre>';
  59. //print_r($xml->matriz);
  60. $arreglo = ($xml->matriz);
  61. echo '</pre>';
  62.  
  63.  
  64. // Cuento el numero de ligas
  65. $num_ligas = count($arreglo[0]['hijo']);
  66. echo "Numero de ligas: $num_ligas <br/>";
  67.  
  68. // Cuento el numero de partidos
  69. $num_partidos = count($arreglo[0]['hijo'][0]['hijo']);
  70. echo "Numero de partidos: $num_partidos <br/>";
  71.  
  72. // Cuento los mercados disponibles
  73. $num_mercados = count($arreglo[0]['hijo'][0]['hijo'][0]['hijo']);
  74. echo "Numero de mercados: $num_mercados <br/>";
  75.  
  76. // Cuento apuestas disponibles de ese mercado
  77. $num_apuestas = count($arreglo[0]['hijo'][0]['hijo'][0]['hijo'][0]['hijo']);
  78. echo "Numero de apuestas para el mercado: $num_apuestas <br/>";
  79.  
  80. for ($i = 0; $i < $num_ligas; $i++) {
  81.  
  82.     if ($arreglo[0]['hijo'][$i]['atributos']['NAME'] != ''){
  83.         // imprime el nombre de la competicion
  84.         echo "<br/>" . $arreglo[0]['hijo'][$i]['atributos']['NAME'] . "<br/>";
  85.        
  86.         $num_partidos = count($arreglo[0]['hijo'][$i]['hijo']);
  87.         $num_apuestas = count($arreglo[0]['hijo'][$i]['hijo'][0]['hijo'][0]['hijo']);
  88.         echo "Numero de partidos: $num_partidos <br/><br/>";
  89.         for ($j = 0; $j < $num_partidos; $j++) {
  90.             // imprime el nombre del partido
  91.             echo $arreglo[0]['hijo'][$i]['hijo'][$j]['atributos']['NAME'] . "<br/>";
  92.             // imprime la fecha del partido
  93.             //echo $arreglo[0]['hijo'][$i]['hijo'][$j]['atributos']['EVENTDATE'] . "<br/>";
  94.             // imprime el enlace del partido
  95.             //echo $arreglo[0]['hijo'][$i]['hijo'][$j]['atributos']['EVENTLINK'] . "<br/>";
  96.             $num_mercados = count($arreglo[0]['hijo'][0]['hijo'][0]['hijo']);
  97.             for ($k = 0; $k < $num_mercados; $k++) {
  98.                 //Nombre del mercado
  99.                 //echo $arreglo[0]['hijo'][$i]['hijo'][$j]['hijo'][$k]['atributos']['NAME'];
  100.                
  101.                 for ($l = 0; $l < $num_apuestas; $l++) {
  102.                     // imprime el nombre de la apuesta
  103.                     echo $arreglo[0]['hijo'][$i]['hijo'][$j]['hijo'][$k]['hijo'][$l]['atributos']['NAME'];
  104.                     // imprime la cuota de la apuesta
  105.                     echo $arreglo[0]['hijo'][$i]['hijo'][$j]['hijo'][$k]['hijo'][$l]['atributos']['ODD'];
  106.                     // imprime el enlace de la apuesta
  107.                     //echo $arreglo[0]['hijo'][$i]['hijo'][$j]['hijo'][$k]['hijo'][$l]['atributos']['PLACEBETLINK'];
  108.                 }
  109.             }
  110.         }
  111.        
  112.     }
  113. }
  114.  
  115.  
  116. ?>
  117.  
  118. </body>
  119. </html>

Última edición por neodani; 09/09/2009 a las 15:01
  #9 (permalink)  
Antiguo 09/09/2009, 15:01
Avatar de neodani  
Fecha de Ingreso: marzo-2007
Mensajes: 1.811
Antigüedad: 17 años, 2 meses
Puntos: 20
Respuesta: Problema simpleXML

¿Podéis darme vuestra opinión y si recorreriais el XML de otra forma?
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




La zona horaria es GMT -6. Ahora son las 01:59.