Foros del Web » Programando para Internet » PHP »

¿Como puedo tratar este XML?

Estas en el tema de ¿Como puedo tratar este XML? en el foro de PHP en Foros del Web. Hola a todos, Tengo unas pequeñas dudas con XML con un pequeño programa que me han pasado, según me han dicho tengo que pasar este ...
  #1 (permalink)  
Antiguo 29/05/2008, 10:31
 
Fecha de Ingreso: abril-2003
Mensajes: 363
Antigüedad: 21 años
Puntos: 3
¿Como puedo tratar este XML?

Hola a todos,

Tengo unas pequeñas dudas con XML con un pequeño programa que me han pasado, según me han dicho tengo que pasar este codigo por metodo POST a una ip:
Código:
<?xml version="1.0" encoding="ISO-8859-1"?>
      <ConsultarTiposHabYPaquetes auth="xml:reservasxml:arcangel:800:08:">
            <FechaLlegada>02/5/08</FechaLlegada>
            <FechaSalida>10/5/08</FechaSalida>
      </ConsultarTiposHabYPaquetes>
Y lo que me devuelve el sistema es:
Código:
<?xml version="1.0" encoding="ISO-8859-1"?>
<ConsultarTiposHabYPaquetes>
 <resultado>OK</resultado>
 <lista_tipos>
  <tipo_habitacion>
      <id_tipo_habitacion>DOB</id_tipo_habitacion>
      <desc_tipo_habitacion>HAB. DOBLES 2 CAMAS</desc_tipo_habitacion>
       <numero_adultos>2</numero_adultos>
  </tipo_habitacion>
  <tipo_habitacion>
       <id_tipo_habitacion>DOM</id_tipo_habitacion>
       <desc_tipo_habitacion>HAB. DOBLE MATRIMONIO</desc_tipo_habitacion>
       <numero_adultos>2</numero_adultos>
  </tipo_habitacion>
  <tipo_habitacion>
       <id_tipo_habitacion>DOV</id_tipo_habitacion>
       <desc_tipo_habitacion>MINUSVALIDOS</desc_tipo_habitacion>
       <numero_adultos>2</numero_adultos>
  </tipo_habitacion>
 </lista_tipos>
</ConsultarTiposHabYPaquetes>
El problema es que me han dicho que esto se procesa por medio de un "parser", que no se genera ningún archivo xml para poderle leer.
Lo voy a programar desde php.
¿Alguno me puede echar una mano y orientarme como hacer o donde encontrar información de los que necesito?

Muchas Gracias
  #2 (permalink)  
Antiguo 29/05/2008, 15:50
Avatar de jam1138
/** @package Moderador */
 
Fecha de Ingreso: julio-2004
Ubicación: sèveR led onieR lE
Mensajes: 9.368
Antigüedad: 19 años, 9 meses
Puntos: 102
Respuesta: ¿Como puedo tratar este XML?

No entiendo exactamente cuál es tu problema. Me pareció solo preguntaste qué podrías utilizar para leer/crear esos XMLs, pues SimpleXML --disponible en PHP5-- te sevirá.
www.php.net/simplexml

__________________
٩(͡๏̯͡๏)۶
» Cómo hacer preguntas de manera inteligente «

"100 años después, la revolución no es con armas, es intelectual y digital"
  #3 (permalink)  
Antiguo 30/05/2008, 15:37
 
Fecha de Ingreso: abril-2003
Mensajes: 363
Antigüedad: 21 años
Puntos: 3
Respuesta: ¿Como puedo tratar este XML?

Cita:
Iniciado por jam1138 Ver Mensaje
No entiendo exactamente cuál es tu problema. Me pareció solo preguntaste qué podrías utilizar para leer/crear esos XMLs, pues SimpleXML --disponible en PHP5-- te sevirá.
www.php.net/simplexml

Gracias por tu respuesta.

¿Y si mi servidor usa PHP4 que alternativas hay?

A lo que me refería es a como mandar por metodo POST el xml y como leer lo que me devuelve el servidor, ya que no tengo que leer un archivo especifico, sino que me lo devuelve directamente.

Muchas Gracias
  #4 (permalink)  
Antiguo 30/05/2008, 15:49
Avatar de jam1138
/** @package Moderador */
 
Fecha de Ingreso: julio-2004
Ubicación: sèveR led onieR lE
Mensajes: 9.368
Antigüedad: 19 años, 9 meses
Puntos: 102
Respuesta: ¿Como puedo tratar este XML?

Cita:
Iniciado por yazo Ver Mensaje
Gracias por tu respuesta.

¿Y si mi servidor usa PHP4 que alternativas hay?

A lo que me refería es a como mandar por metodo POST el xml y como leer lo que me devuelve el servidor, ya que no tengo que leer un archivo especifico, sino que me lo devuelve directamente.

Muchas Gracias
Eso es me suena a SOAP. ¿Seguro que no es SOAP?, porque de ser así tienes librerías para trabjarlo.

Como sea, para tratar con XML en PHP4 puedes hacer uso de la extensión XML Parser, aunque --dependiendo de cómo vayas a trabajar-- te puede ser útil el paquete XML_Serialize de PEAR.

www.php.net/book.xml
pear.php.net/package/XML_Serializer

Para enviar por POST la información necesitarás usar CURL
www.php.net/book.curl

Muevo tu tema al foro PHP.
__________________
٩(͡๏̯͡๏)۶
» Cómo hacer preguntas de manera inteligente «

"100 años después, la revolución no es con armas, es intelectual y digital"
  #5 (permalink)  
Antiguo 03/06/2008, 10:35
 
Fecha de Ingreso: abril-2003
Mensajes: 363
Antigüedad: 21 años
Puntos: 3
Respuesta: ¿Como puedo tratar este XML?

Hola,

He conseguido algo pero parcialmente, ya que funciona en mi servidor de pruebas, pero en internet no funciona.
El código es el siguiente:

index.php
Código PHP:
/**
 * xml2array() will convert the given XML text to an array in the XML structure.
 * Link: http://www.bin-co.com/php/scripts/xml2array/
 * Arguments : $contents - The XML text
 *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
 * Return: The parsed XML in an array form.
 */
function xml2array($contents, $get_attributes=1) {
    if(!$contents) return array();

    if(!function_exists('xml_parser_create')) {
        //print "'xml_parser_create()' function not found!";
        return array();
    }
    //Get the XML parser of PHP - PHP must have this module for the parser to work
    $parser = xml_parser_create();
    xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
    xml_parser_set_option( $parser, XML_OPTION_SKIP_WHITE, 1 );
    xml_parse_into_struct( $parser, $contents, $xml_values );
    xml_parser_free( $parser );

    if(!$xml_values) return;//Hmm...

    //Initializations
    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();

    $current = &$xml_array;

    //Go through the tags.
    foreach($xml_values as $data) {
        unset($attributes,$value);//Remove existing values, or there will be trouble

        //This command will extract these variables into the foreach scope
        // tag(string), type(string), level(int), attributes(array).
        extract($data);//We could use the array by itself, but this cooler.

        $result = '';
        if($get_attributes) {//The second argument of the function decides this.
            $result = array();
            if(isset($value)) $result['value'] = $value;

            //Set the attributes too.
            if(isset($attributes)) {
                foreach($attributes as $attr => $val) {
                    if($get_attributes == 1) $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
                    /**  :TODO: should we change the key name to '_attr'? Someone may use the tagname 'attr'. Same goes for 'value' too */
                }
            }
        } elseif(isset($value)) {
            $result = $value;
        }

        //See tag status and do the needed.
        if($type == "open") {//The starting of the tag '<tag>'
            $parent[$level-1] = &$current;

            if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
                $current[$tag] = $result;
                $current = &$current[$tag];

            } else { //There was another element with the same tag name
                if(isset($current[$tag][0])) {
                    array_push($current[$tag], $result);
                } else {
                    $current[$tag] = array($current[$tag],$result);
                }
                $last = count($current[$tag]) - 1;
                $current = &$current[$tag][$last];
            }

        } elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
            //See if the key is already taken.
            if(!isset($current[$tag])) { //New Key
                $current[$tag] = $result;

            } else { //If taken, put all things inside a list(array)
                if((is_array($current[$tag]) and $get_attributes == 0)//If it is already an array...
                        or (isset($current[$tag][0]) and is_array($current[$tag][0]) and $get_attributes == 1)) {
                    array_push($current[$tag],$result); // ...push the new element into that array.
                } else { //If it is not an array...
                    $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
                }
            }

        } elseif($type == 'close') { //End of tag '</tag>'
            $current = &$parent[$level-1];
        }
    }

    return($xml_array);
}



require_once('post_xml.php');

$xml ="<?xml version='1.0' encoding='ISO-8859-1'?>
      <ConsultarTiposHabYPaquetes auth='xml:reservasxml:arcangel:800:08:'>
            <FechaLlegada>10/6/08</FechaLlegada>
            <FechaSalida>20/6/08</FechaSalida>
      </ConsultarTiposHabYPaquetes>";
      
$url ='http://xx.xx.xx.xx';
$port = 606;

$response = xml_post($xml, $url, $port);

//imprimimos la respuesta
$resultado = xml2array($response);

function echo_array($array,$return_me=false){
    if(is_array($array) == false){
        $return = "The provided variable is not an array.";
    }else{
        foreach($array as $name=>$value){
            if(is_array($value)){
                $return .= "";
                $return .= "['<b>$name</b>'] {<div style='margin-left:10px;'>\n";
                $return .= echo_array($value,true);
                $return .= "</div>}";
                $return .= "\n\n";
            }else{
                if(is_string($value)){
                    $value = "\"$value\"";
                }
                $return .= "['<b>$name</b>'] = $value\n\n";
            }
        }
    }
    if($return_me == true){
        return $return;
    }else{
        echo "<pre>".$return."</pre>";
    }
}

echo_array($resultado);
post_xml.php
Código PHP:
// open a http channel, transmit data and return received buffer
    
function xml_post($post_xml$url$port)
    {
        
$user_agent $_SERVER['HTTP_USER_AGENT'];

        
$ch curl_init();    // initialize curl handle
        
curl_setopt($chCURLOPT_URL$url); // set url to post to
        
curl_setopt($chCURLOPT_FAILONERROR1);              // Fail on errors
        
curl_setopt($chCURLOPT_FOLLOWLOCATION1);    // allow redirects
        
curl_setopt($chCURLOPT_RETURNTRANSFER,1); // return into a variable
        
curl_setopt($chCURLOPT_PORT$port);            //Set the port number
        
curl_setopt($chCURLOPT_TIMEOUT15); // times out after 15s
        
curl_setopt($chCURLOPT_POSTFIELDS$post_xml); // add POST fields
        
curl_setopt($chCURLOPT_USERAGENT$user_agent);

        if(
$port==443)
        {
            
curl_setopt($chCURLOPT_SSL_VERIFYHOST,  2);
            
curl_setopt($chCURLOPT_SSL_VERIFYPEER0);
        }

        
$data curl_exec($ch);

        
curl_close($ch);

        return 
$data;
    } 
Creo que falla por el curl, pero nose exactamente en que, porque la version es la misma en internet que en mi servidor.
¿Me podeis ayudar?

Muchas Gracias
  #6 (permalink)  
Antiguo 03/06/2008, 11:20
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: ¿Como puedo tratar este XML?

Hola yazo,

Cuando dices que falla, ¿Que error te marca?,

Saludos.
  #7 (permalink)  
Antiguo 03/06/2008, 11:27
 
Fecha de Ingreso: abril-2003
Mensajes: 363
Antigüedad: 21 años
Puntos: 3
Respuesta: ¿Como puedo tratar este XML?

Hola GatorV,

Tengo dos alojamientos en servidores distintos, en uno da el siguiente error:

Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in /home/dominio/public_html/xml/post_xml.php on line 10

En el otro no me da el error pero no muestra nada por pantalla.

Muchas Gracias
  #8 (permalink)  
Antiguo 03/06/2008, 11:31
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: ¿Como puedo tratar este XML?

Hola yazo,

En tu primer hosting, el error que te indica es que no puedes poner CURLOPT_FOLLOWLOCATION ya que tienes que activado el safe_mode y la directiva open_basedir.

Puedes quitar esa opcion en tu curl_setopt y probar si sirve tu código.

En tu segundo server seguramente tienes desactivada la opción de display_errors, por lo que deberás activarla para que te muestre porque esta fallando.

Saludos.
  #9 (permalink)  
Antiguo 03/06/2008, 11:55
 
Fecha de Ingreso: abril-2003
Mensajes: 363
Antigüedad: 21 años
Puntos: 3
Respuesta: ¿Como puedo tratar este XML?

Hola GatorV,

He realizado el cambio y ahora no muestra ningún error, he revisado el log de errores de los dos servidores pero no muestra nada.
¿Puede ser porque en mi servidor de pruebas tengo php5 y en el internet se usa php4?

Gracias
  #10 (permalink)  
Antiguo 03/06/2008, 11:59
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: ¿Como puedo tratar este XML?

Puede ser una causa, aunque esta muy extraño que no te guarda nada en los logs, ¿estas seguro que tienes los mismos módulos que en tu localhost?, puedes comprobarlo usando phpinfo();

Saludos.
  #11 (permalink)  
Antiguo 03/06/2008, 12:16
 
Fecha de Ingreso: abril-2003
Mensajes: 363
Antigüedad: 21 años
Puntos: 3
Respuesta: ¿Como puedo tratar este XML?

En efecto, acabo de cambiar la version del servidor de pruebas por php4 y no funciona.
¿Teneis algún codigo o manual que me pueda servir para php4?

Muchas Gracias
  #12 (permalink)  
Antiguo 03/06/2008, 15:02
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: ¿Como puedo tratar este XML?

Hola yazo4,

Deberías de identificar exactamente que problema en exacto tienes de usar PHP5 -> PHP4.

Saludos.
  #13 (permalink)  
Antiguo 04/06/2008, 16:10
 
Fecha de Ingreso: abril-2003
Mensajes: 363
Antigüedad: 21 años
Puntos: 3
Respuesta: ¿Como puedo tratar este XML?

Hola a todos,

He revisado el log del servidor privado y me da el siguiente error:
Código:
PHP Notice:  Undefined variable:  return in /Servidor/pruebas/xml/index.php on line 150
Que coincide con la línea:
Código PHP:
echo "<pre>".$return."</pre>"
¿A que se puede deber?

Gracias por la ayuda
  #14 (permalink)  
Antiguo 04/06/2008, 16:17
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: ¿Como puedo tratar este XML?

claramente dice $return no esta definida....

debes definirla antes de poder usarla... suerte!
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #15 (permalink)  
Antiguo 04/06/2008, 16:47
 
Fecha de Ingreso: abril-2003
Mensajes: 363
Antigüedad: 21 años
Puntos: 3
Respuesta: ¿Como puedo tratar este XML?

He probado a quitar esa función que lo unico que hace es mostrar el array ordenado y sigue sin mostrarse.
El problema he visto que está en la función que envia y recibe la información del XML, es decir, la que envía por método POST el XML y lee el resultado.
¿Conoceis alguna que funcione en PHP4?

Muchas gracias
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 10:49.