Foros del Web » Programando para Internet » PHP »

¿Cómo leer XML directamente con PHP?

Estas en el tema de ¿Cómo leer XML directamente con PHP? en el foro de PHP en Foros del Web. Buenas amigos, tengo la siguiente duda. Resulta que estoy haciendo una solicitud a un WFS, el cual me devuelve la respuesta en formato XML. Ahora ...
  #1 (permalink)  
Antiguo 23/05/2012, 13:00
Avatar de Heiroon  
Fecha de Ingreso: junio-2010
Ubicación: Caracas, Venezuela - Por ahora...
Mensajes: 495
Antigüedad: 13 años, 9 meses
Puntos: 63
Exclamación ¿Cómo leer XML directamente con PHP?

Buenas amigos,

tengo la siguiente duda. Resulta que estoy haciendo una solicitud a un WFS, el cual me devuelve la respuesta en formato XML. Ahora bien, quiero interpretar ese código XML para insertarlo en Base de datos.

hasta ahora tengo lo siguiente:


Código PHP:
Ver original
  1. //Definición de los parámetros a enviar en la petición.
  2.    
  3.     $service  = "SERVICE=WFS";
  4.     $request  = "REQUEST=GetFeature";
  5.     $output   = "OUTPURFORMAT=text/xml;subtipo=gml/3.1.1";
  6.     $typename = "TYPENAME=C1C_Mobile_c1c_mobile:Eventos";
  7.    
  8.     $params = "?$service&$request&$output&$typename";
  9.    
  10.     try
  11.     {
  12.         $wfsReq = WFS_REQ_PATH.$params;
  13.         $response = file_get_contents($wfsReq);
  14.        
  15.         header('Content-type: text/xml');
  16.        
  17.         echo $response;
  18.        
  19.                 //¿Cómo interpreto el XML en Strings con su campo y valor?
  20.        
  21.     }
  22.     catch (Exception $e)
  23.     {
  24.         echo "Something went wrong: ".$e;
  25.     }


Lo que quiero hacer ahora es interpretar el XML y devolver los campos y valores en string sencillas. ¿Es posible hacer esto? ¿Cómo se hace?

Muchas gracias de antemano por su ayuda!
__________________
Gmail : [email protected]
Twitter: @heiroon

I'm back!
  #2 (permalink)  
Antiguo 23/05/2012, 13:07
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: ¿Cómo leer XML directamente con PHP?

Puedes usar SimpleXML para parsear el XML y poderlo manipular.

Saludos.
  #3 (permalink)  
Antiguo 23/05/2012, 13:13
Avatar de skiper0125  
Fecha de Ingreso: octubre-2010
Ubicación: $this->Mexico('Toluca');
Mensajes: 1.127
Antigüedad: 13 años, 5 meses
Puntos: 511
Respuesta: ¿Cómo leer XML directamente con PHP?

Hola que tal

te recomiendo que leas simple xml

Saludos.

ya me gano GatorV
__________________
Recuerda que estamos aquí para orientarte, y no para hacer tu trabajo.
Si mi aporte fue de ayuda, recuerda que agradecer no cuesta nada +1

Skiper0125
  #4 (permalink)  
Antiguo 23/05/2012, 13:27
Avatar de Heiroon  
Fecha de Ingreso: junio-2010
Ubicación: Caracas, Venezuela - Por ahora...
Mensajes: 495
Antigüedad: 13 años, 9 meses
Puntos: 63
Exclamación Respuesta: ¿Cómo leer XML directamente con PHP?

Gracias a los dos, precisamente estoy usando simpleXML pero no consigo implementarlo

no me esta tomando $response como un objeto XML, pues me devuelve todo en blanco...

estoy probando declararlo de esta manera, pero nada!


Código PHP:
Ver original
  1. $service  = "SERVICE=WFS";
  2.     $request  = "REQUEST=GetFeature";
  3.     $output   = "OUTPURFORMAT=text/xml;subtipo=gml/3.1.1";
  4.     $typename = "TYPENAME=C1C_Mobile_c1c_mobile:Eventos";
  5.    
  6.  
  7.     try
  8.     {
  9.                
  10.         $response = simplexml_load_file(rawurlencode(WFS_REQ_PATH."?".urlencode($service)."&".urlencode($request)."&".urlencode($output)."&".urlencode($typename)));
  11.        
  12.     }
  13.     catch (Exception $e)
  14.     {
  15.         echo "Something went wrong: ".$e;
  16.     }

La idea de esto es utilizar el xpath para llamar los campos que necesito, pero no llego a este punto.

Ayuda por favor!
__________________
Gmail : [email protected]
Twitter: @heiroon

I'm back!
  #5 (permalink)  
Antiguo 23/05/2012, 13:30
Avatar de skiper0125  
Fecha de Ingreso: octubre-2010
Ubicación: $this->Mexico('Toluca');
Mensajes: 1.127
Antigüedad: 13 años, 5 meses
Puntos: 511
Respuesta: ¿Cómo leer XML directamente con PHP?

Hola que tal.


Te dejo este aoprte checalo está muy bien explicado http://www.forosdelweb.com/f18/aport...ml-dom-792348/

Saludos
__________________
Recuerda que estamos aquí para orientarte, y no para hacer tu trabajo.
Si mi aporte fue de ayuda, recuerda que agradecer no cuesta nada +1

Skiper0125
  #6 (permalink)  
Antiguo 23/05/2012, 13:31
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: ¿Cómo leer XML directamente con PHP?

Primero obtén como antes el XML dentro de $response, y luego le pasas esta variable a simplexml_load_string.

Saludos.
  #7 (permalink)  
Antiguo 23/05/2012, 13:45
Avatar de Heiroon  
Fecha de Ingreso: junio-2010
Ubicación: Caracas, Venezuela - Por ahora...
Mensajes: 495
Antigüedad: 13 años, 9 meses
Puntos: 63
Exclamación Respuesta: ¿Cómo leer XML directamente con PHP?

Creo que hay un problema... Y es que el codigo que me devuelve esta en GML

este es un ejemplo de un nodo:

Código XML:
Ver original
  1. <gml:featureMember>
  2.         <C1C_Mobile_c1c_mobile:Eventos gml:id="F27__4">
  3.         <C1C_Mobile_c1c_mobile:OBJECTID>4</C1C_Mobile_c1c_mobile:OBJECTID>
  4.         <C1C_Mobile_c1c_mobile:Tutulo_del_Evento>CONFORMACIÓN DE CAMPO DEPORTIVO</C1C_Mobile_c1c_mobile:Tutulo_del_Evento>
  5.         <C1C_Mobile_c1c_mobile:Direccion>La Charneca, San Agustin</C1C_Mobile_c1c_mobile:Direccion>
  6.         <C1C_Mobile_c1c_mobile:Descripcion>la Alcaldía Metropolitana traslada 2 Tanques de Agua</C1C_Mobile_c1c_mobile:Descripcion>
  7.         <C1C_Mobile_c1c_mobile:Fecha>2011-04-08T21:55:34</C1C_Mobile_c1c_mobile:Fecha>
  8.         <C1C_Mobile_c1c_mobile:Hora>9:00 a.m.</C1C_Mobile_c1c_mobile:Hora>
  9.         <C1C_Mobile_c1c_mobile:Estatus>0</C1C_Mobile_c1c_mobile:Estatus>
  10.         <C1C_Mobile_c1c_mobile:Tipo_de_Evento>3</C1C_Mobile_c1c_mobile:Tipo_de_Evento>
  11.         <C1C_Mobile_c1c_mobile:MUNICIPIO>1</C1C_Mobile_c1c_mobile:MUNICIPIO>
  12.         <C1C_Mobile_c1c_mobile:PARROQUIA>1</C1C_Mobile_c1c_mobile:PARROQUIA>
  13.         <C1C_Mobile_c1c_mobile:SHAPE>
  14.             <gml:Point>
  15.                 <gml:pos>-7447172.5109000001 1174911.2608000003</gml:pos>
  16.             </gml:Point>
  17.         </C1C_Mobile_c1c_mobile:SHAPE>
  18.         </C1C_Mobile_c1c_mobile:Eventos>
  19.     </gml:featureMember>


Ese se interpreta igual?
__________________
Gmail : [email protected]
Twitter: @heiroon

I'm back!
  #8 (permalink)  
Antiguo 23/05/2012, 14:01
Avatar de Heiroon  
Fecha de Ingreso: junio-2010
Ubicación: Caracas, Venezuela - Por ahora...
Mensajes: 495
Antigüedad: 13 años, 9 meses
Puntos: 63
Exclamación Respuesta: ¿Cómo leer XML directamente con PHP?

Bueno, creo que eso del GML no tiene nada que ver... Sin embargo estoy haciendo lo siguiente y me devuelve un objeto vacio...

Código PHP:
Ver original
  1. header("Content-type: text/html; charset=utf-8");
  2.     //header('Content-type: text/xml');
  3.    
  4.     //Definición de los parámetros a enviar en la petición.
  5.    
  6.     $service  = "SERVICE=WFS";
  7.     $request  = "REQUEST=GetFeature";
  8.     $output   = "OUTPURFORMAT=text/xml;subtipo=gml/3.1.1";
  9.     $typename = "TYPENAME=C1C_Mobile_c1c_mobile:Eventos";
  10.    
  11.     $params = "?$service&$request&$output&$typename";
  12.    
  13.     try
  14.     {
  15.         $wfsReq = WFS_REQ_PATH.$params;
  16.         $response = file_get_contents($wfsReq);
  17.        
  18.         $xml = new SimpleXMLElement($response);
  19.         var_dump($xml);
  20.        
  21.     }
  22.     catch (Exception $e)
  23.     {
  24.         echo "Something went wrong: ".$e;
  25.     }

y me devuelve:

object(SimpleXMLElement)#1 (0) { }
__________________
Gmail : [email protected]
Twitter: @heiroon

I'm back!
  #9 (permalink)  
Antiguo 23/05/2012, 14:23
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: ¿Cómo leer XML directamente con PHP?

Ya te indique más arriba, debes de usar simplexml_load_string.

Saludos.
  #10 (permalink)  
Antiguo 23/05/2012, 14:29
Avatar de Heiroon  
Fecha de Ingreso: junio-2010
Ubicación: Caracas, Venezuela - Por ahora...
Mensajes: 495
Antigüedad: 13 años, 9 meses
Puntos: 63
Desacuerdo Respuesta: ¿Cómo leer XML directamente con PHP?

Cita:
Iniciado por GatorV Ver Mensaje
Ya te indique más arriba, debes de usar simplexml_load_string.

Saludos.
No hay diferencia, me devuelve object(SimpleXMLElement)#1 (0) { } colocandole simplexml_load_string
__________________
Gmail : [email protected]
Twitter: @heiroon

I'm back!
  #11 (permalink)  
Antiguo 23/05/2012, 14:36
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: ¿Cómo leer XML directamente con PHP?

Lee lo siguiente:

http://us3.php.net/manual/en/simplex...les-errors.php
  #12 (permalink)  
Antiguo 24/05/2012, 09:54
Avatar de Heiroon  
Fecha de Ingreso: junio-2010
Ubicación: Caracas, Venezuela - Por ahora...
Mensajes: 495
Antigüedad: 13 años, 9 meses
Puntos: 63
Exclamación Respuesta: ¿Cómo leer XML directamente con PHP?

GatorV, muchas gracias por la ayuda que me has prestado hasta ahora! Implemente lo de los errores y me dice lo mismo. Que el archivo está vacio.

Ahora bien, voy a mostrar un ejemplo completo de la estructura del XML que necesito convertir. Por razones de seguridad, cambie la información, sin embargo esto no tiene importancia relevante.

Acá esta:


Código XML:
Ver original
  1. <wfs:FeatureCollection xmlns:Mobile="http://www.ejemplo.com/MapServer/WFSServer" xmlns:gml="http://www.opengis.net/gml" xmlns:wfs="http://www.opengis.net/wfs" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="www.ejemplo.com/MapServer/WFSServerhttp://www.ejemplo.com/MapServer/WFSServer?request=DescribeFeatureType%26version=1.1.0%26typename=TestLayer http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">
  2.                 <gml:boundedBy>
  3.                     <gml:Envelope srsName="urn:ogc:def:crs:EPSG:6.9:3857">
  4.                         <gml:lowerCorner>-7493200.6969000008 1138783.0582999997</gml:lowerCorner>
  5.                         <gml:upperCorner>-7416878.3242000006 1184981.5566999987</gml:upperCorner>
  6.                     </gml:Envelope>
  7.                 </gml:boundedBy>
  8.                 <gml:featureMember>
  9.                     <Mobile:Eventos gml:id="1">
  10.                     <Mobile:OBJECTID>4</Mobile:OBJECTID>
  11.                     <Mobile:Tutulo_del_Evento>Evento de prueba</Mobile:Tutulo_del_Evento>
  12.                     <Mobile:Direccion>Dirección de prueba</Mobile:Direccion>
  13.                     <Mobile:Descripcion>Descripción de prueba</Mobile:Descripcion>
  14.                     <Mobile:Fecha>2011-03-18T21:55:34</Mobile:Fecha>
  15.                     <Mobile:Hora>11:00 a.m.</Mobile:Hora>
  16.                     <Mobile:Estatus>0</Mobile:Estatus>
  17.                     <Mobile:Tipo_de_Evento>3</Mobile:Tipo_de_Evento>
  18.                     <Mobile:MUNICIPIO>1</Mobile:MUNICIPIO>
  19.                     <Mobile:PARROQUIA>1</Mobile:PARROQUIA>
  20.                     <Mobile:SHAPE>
  21.                         <gml:Point>
  22.                             <gml:pos>-3447172.5109000001 2174911.2608000003</gml:pos>
  23.                         </gml:Point>
  24.                     </Mobile:SHAPE>
  25.                     </Mobile:Eventos>
  26.                 </gml:featureMember>
  27.                 <gml:featureMember>
  28.             </wfs:FeatureCollection>
__________________
Gmail : [email protected]
Twitter: @heiroon

I'm back!
  #13 (permalink)  
Antiguo 24/05/2012, 11:13
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: ¿Cómo leer XML directamente con PHP?

Código PHP:
Ver original
  1. <?php
  2. $sXML = <<<XML
  3. <wfs:FeatureCollection xmlns:Mobile="http://www.ejemplo.com/MapServer/WFSServer" xmlns:gml="http://www.opengis.net/gml" xmlns:wfs="http://www.opengis.net/wfs" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="www.ejemplo.com/MapServer/WFSServerhttp://www.ejemplo.com/MapServer/WFSServer?request=DescribeFeatureType%26version=1.1.0%26typename=TestLayer http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">
  4.     <gml:boundedBy>
  5.         <gml:Envelope srsName="urn:ogc:def:crs:EPSG:6.9:3857">
  6.             <gml:lowerCorner>-7493200.6969000008 1138783.0582999997</gml:lowerCorner>
  7.             <gml:upperCorner>-7416878.3242000006 1184981.5566999987</gml:upperCorner>
  8.         </gml:Envelope>
  9.     </gml:boundedBy>
  10.     <gml:featureMember>
  11.         <Mobile:Eventos gml:id="1">
  12.             <Mobile:OBJECTID>4</Mobile:OBJECTID>
  13.             <Mobile:Tutulo_del_Evento>Evento de prueba</Mobile:Tutulo_del_Evento>
  14.             <Mobile:Direccion>Dirección de prueba</Mobile:Direccion>
  15.             <Mobile:Descripcion>Descripción de prueba</Mobile:Descripcion>
  16.             <Mobile:Fecha>2011-03-18T21:55:34</Mobile:Fecha>
  17.             <Mobile:Hora>11:00 a.m.</Mobile:Hora>
  18.             <Mobile:Estatus>0</Mobile:Estatus>
  19.             <Mobile:Tipo_de_Evento>3</Mobile:Tipo_de_Evento>
  20.             <Mobile:MUNICIPIO>1</Mobile:MUNICIPIO>
  21.             <Mobile:PARROQUIA>1</Mobile:PARROQUIA>
  22.             <Mobile:SHAPE>
  23.                 <gml:Point>
  24.                     <gml:pos>-3447172.5109000001 2174911.2608000003</gml:pos>
  25.                 </gml:Point>
  26.             </Mobile:SHAPE>
  27.         </Mobile:Eventos>
  28.     </gml:featureMember>
  29. </wfs:FeatureCollection>
  30. XML;
  31.  
  32. $oXML = simplexml_load_string($sXML);
  33. if (!$oXML) {
  34.     echo "Failed loading XML\n";
  35.     foreach(libxml_get_errors() as $error) {
  36.         echo "\t", $error->message . "<br />";
  37.     }
  38. }

Eso me indica esto:
Cita:
Failed loading XML Input is not proper UTF-8, indicate encoding ! Bytes: 0xF3 0x6E 0x20 0x64
Saludos.

Última edición por GatorV; 24/05/2012 a las 11:21
  #14 (permalink)  
Antiguo 24/05/2012, 12:09
Avatar de Heiroon  
Fecha de Ingreso: junio-2010
Ubicación: Caracas, Venezuela - Por ahora...
Mensajes: 495
Antigüedad: 13 años, 9 meses
Puntos: 63
Pregunta Respuesta: ¿Cómo leer XML directamente con PHP?

Entiendo, pero el problema que tengo es que yo hago una petición al WFS, y el me devuelve el XML sin:

Código PHP:
Ver original
  1. <?xml version = '1.0' encoding = 'UTF-8'?>

y viene dentro de una variable $response. Así que no se como podría agregarselo o agregarle lo que tu usas. Lo de:

Código PHP:
Ver original
  1. <<<XML  XML;

¿como podría hacer esto?

Y de nuevo muchas gracias por tu ayuda!
__________________
Gmail : [email protected]
Twitter: @heiroon

I'm back!
  #15 (permalink)  
Antiguo 29/05/2012, 10:11
Avatar de Heiroon  
Fecha de Ingreso: junio-2010
Ubicación: Caracas, Venezuela - Por ahora...
Mensajes: 495
Antigüedad: 13 años, 9 meses
Puntos: 63
De acuerdo Respuesta: ¿Cómo leer XML directamente con PHP?

Buenas gente... En vista de que nadie me pudo ayudar con esto, y yo lo logre resolver, acá dejo cual era el problema!

La cuestion es que el simpleXML no reconocia el codigo por los "gml:" de las etiquetas... Así que se los elimine, y efectivamente funciono...

quedando de este modo:


Código XML:
Ver original
  1. <wfs:FeatureCollection xmlns:Mobile="http://www.ejemplo.com/MapServer/WFSServer" xmlns:gml="http://www.opengis.net/gml" xmlns:wfs="http://www.opengis.net/wfs" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="www.ejemplo.com/MapServer/WFSServerhttp://www.ejemplo.com/MapServer/WFSServer?request=DescribeFeatureType%26version=1.1.0%26typename=TestLayer http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">
  2. * * <boundedBy>
  3. * * * * <Envelope srsName="urn:ogc:def:crs:EPSG:6.9:3857">
  4. * * * * * * <lowerCorner>-7493200.6969000008 1138783.0582999997</lowerCorner>
  5. * * * * * * <upperCorner>-7416878.3242000006 1184981.5566999987</upperCorner>
  6. * * * * </Envelope>
  7. * * </boundedBy>
  8. * * <featureMember>
  9. * * * * <Eventos gml:id="1">
  10. * * * * * * <OBJECTID>4</OBJECTID>
  11. * * * * * * <Tutulo_del_Evento>Evento de prueba</Tutulo_del_Evento>
  12. * * * * * * <Direccion>Dirección de prueba</Direccion>
  13. * * * * * * <Descripcion>Descripción de prueba</Descripcion>
  14. * * * * * * <Fecha>2011-03-18T21:55:34</Fecha>
  15. * * * * * * <Hora>11:00 a.m.</Hora>
  16. * * * * * * <Estatus>0</Estatus>
  17. * * * * * * <Tipo_de_Evento>3</Tipo_de_Evento>
  18. * * * * * * <MUNICIPIO>1</MUNICIPIO>
  19. * * * * * * <PARROQUIA>1</PARROQUIA>
  20. * * * * * * <SHAPE>
  21. * * * * * * * * <Point>
  22. * * * * * * * * * * <pos>-3447172.5109000001 2174911.2608000003</pos>
  23. * * * * * * * * </Point>
  24. * * * * * * </SHAPE>
  25. * * * * </Eventos>
  26. * * </featureMember>
  27. </wfs:FeatureCollection>

Muchas gracias a mi hehe
__________________
Gmail : [email protected]
Twitter: @heiroon

I'm back!

Etiquetas: string, xml
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 11:15.