Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   PHP (https://www.clubdelphi.com/foros/forumdisplay.php?f=15)
-   -   PHP y XML (Crear un documento XML pasandole yo las variables) (https://www.clubdelphi.com/foros/showthread.php?t=35540)

papulo 13-09-2006 18:26:09

PHP y XML (Crear un documento XML pasandole yo las variables)
 
No es excesivamente complejo lo que quiero hacer, crear una pagina "index.php" (por ejemplo) y hacer que se acceda a ella introduciendole unos parametros por la url "www.yoquese/index.php&variable1=2&variable2=papichulo"
Luego, las capturo y las proceso
en el codigo PHP (mi intención es hacer una consulta en una DB en firebird) y devolver un documento xml.

¿Problemas?
Con el XML y el PHP todos.
Ya que si he encontrado como tratar la consulta y demás, pero para crear el archivo XML me las estoy viendo y deseando, a parte de que en este campo soy totalmente novato y no me deja usar las instrucciones.

Uso PHP 5.1.4 y me dice que :

Loaded extensions :

bcmath, calendar, com_dotnet, ctype, date, ftp, hash, iconv, odbc, pcre, Reflection, session, libxml, standard, tokenizer, zlib, SimpleXML, dom, SPL, wddx, xml, xmlreader, xmlwriter, apache, gettext, interbase, mbstring, mysql, mysqli, xmlrpc


Pero siguiendo el siguiente ejemplo:
Código PHP:

<?php
include "libreria_web.php";// query database for records
$query "SELECT ref_type, id_part_type, xml_tag FROM technical_items WHERE xml_tag<>''";
$consulta consulta_bd($query);

while (
$fila ibase_fetch_object ($consulta))
{
      
// create DomDocument object
      
$doc domxml_new_doc("1.0");
      
// add root node
      
$root $doc->add_root("reference");
      
// iterate through result set
      
while(list($ref_num$id_part_type$xml_tag) = ibase_fetch_row($result))
      {
            
// create item node
            
$record $root->new_child("reference""");
            
$record->set_attribute("ref_num"$ref_num);
            
// attach title and artist as children of item node
            
$record->new_child("id_part_type"$id_part_type);
            
$record->new_child("xml_tag"$xml_tag);
      }

// print the tree
echo $doc->dumpmem();
}
?>

Que está basado en:

Código PHP:

<?php
 
// query database for records 
$connection mysql_connect("cdserver""joe""cool") or die ("Unable toconnect!"); 
mysql_select_db("db712") or die ("Unable to select database!"); 
$query "SELECT id, title, artist FROM cds"
$result mysql_query($query) or die ("Error in query: $query. " mysql_error()); 

if (
mysql_num_rows($result) > 0
{
      
// create DomDocument object 
      
$doc new_xmldoc("1.0"); 

      
// add root node 
      
$root $doc->add_root("cds"); 

      
// iterate through result set 
      
while(list($id$title$artist) = mysql_fetch_row($result)) 
      {
            
// create item node 
            
$record $root->new_child("cd"""); 
             
record->set_attribute("id"$id); 

            
// attach title and artist as children of item node 
            
$record->new_child("title"$title); 
            
$record->new_child("artist"$artist); 
      } 

// print the tree 
echo $doc->dumpmem(); 
}   
// close connection 
mysql_close($connection); 
?>


Obviamente el primero lo he modificado según mi (bastante nulo) criterio, pero bueno, hasta aquí puedo leer.

¿Sugerencias?

Saluditos a todos los del foro, que sois unos cracks.

dec 13-09-2006 18:38:32

Hola,

¿Es obligado utilizar las extensiones y funciones que expones? ¿Te planteaste escribir el archivo XML "a mano" y luego enviarlo al cliente? Pregunto... :)

roman 13-09-2006 18:45:51

Bueno pero, ¿cuál es el problema? "No me deja usar las instrucciones" no dice nada. ¿Por qué no te deja? ¿Qué error marca?

// Saludos

papulo 13-09-2006 18:53:38

Ahora lo estoy generando a mano en un archivo PHP y lo enviaré tal cual, cosa que no se me había ocurrido antes por inexperiencia.

Roman:Simplemente me da un error, me dice que esa función no es valida (y nada mas, barrabas).

roman 13-09-2006 19:09:09

Yo no sé si te has percatado que tú problema no está en no poder generar archivos XML. No has llegado al punto de saber si esas funciones te sirven o no dado que por alguna razón php no las está reconociendo. ¿No es un poco prematuro para desechar una opción?

// Saludos

papulo 14-09-2006 10:29:22

No las desecho, Roman, las aparco temporalmente para resolver el problema de forma artesanal, dado que se me echa el tiempo encima. Pero si quiero saber por que no me han funcionado y como hacer que funcionen correctamente.

Como aun estamos en un estado prematuro en lo que estoy intentando hacer (pruebas de concepto y demás), no pasa nada porque comience haciendolo así.

Gracias por la paciencia a todos ;).

Saludos,
Papulo.

Ñuño Martínez 14-09-2006 13:38:38

Echando un vistacillo, así por encima, he encontrado un detalle que no ha comentado nadie. He marcado unas líneas con el comentario "// <--- AQUÍ":

Código PHP:

 <?php
include "libreria_web.php";// query database for records
$query "SELECT ref_type, id_part_type, xml_tag FROM technical_items WHERE xml_tag<>''";
$consulta consulta_bd($query);

while (
$fila ibase_fetch_object ($consulta))  // <--- AQUÍ
{
      
// create DomDocument object
      
$doc domxml_new_doc("1.0"); // <--- AQUÍ
      // add root node
      
$root $doc->add_root("reference");
      
// iterate through result set
      
while(list($ref_num$id_part_type$xml_tag) = ibase_fetch_row($result))
      {
            
// create item node
            
$record $root->new_child("reference""");
            
$record->set_attribute("ref_num"$ref_num);
            
// attach title and artist as children of item node
            
$record->new_child("id_part_type"$id_part_type);
            
$record->new_child("xml_tag"$xml_tag);
      }

// print the tree
echo $doc->dumpmem(); // <--- AQUÍ
}  // <--- AQUÍ
?>

Tal como lo pones, y adivinando qué es lo que hace la función domxml_new_doc, este código crea un archivo XML por cada línea que devuelve la consulta ya que la creación del archivo y su volcado están dentro del bucle y, si no he entendido mal, eso no es lo que quieres.

Por otro lado, la línea
Código PHP:

include "libreria_web.php";// query database for records 

no me inspira confianza en absoluto. ¿Seguro que quieres incluir "librería_web.php"? ¿Qué funciones, objetos o trabajos contiene?

papulo 15-09-2006 13:04:02

La libreria_web.php es un archivo mio donde voy poniendo funciones que uso a menudo, como acceso a la base de datos en firebird o cosas que surjan.

Código PHP:

<?
//******************************************************************************
// Funcion de conexion a al BD y consulta de $query
//******************************************************************************
function consulta_bd($query)
{
$connection ibase_pconnect ('Dev1:d:/Una/Ruta/AlabasededatosDB.FDB''usuario''contraseña');
$sql $query//Insertamos la consulta que queremos realizar
$consulta ibase_query($connection$sql);
return 
$consulta;
}
//******************************************************************************
//Función de limpieza de la referencia
//******************************************************************************
function CleanUpSpaces($ref)
{
    for  (
$i 0;$i<=strlen($ref);$i++)
    {
        if
           ((((
ord($ref[$i]))>=48) and ((ord($ref[$i]))<=57))
        or (((
ord($ref[$i]))>=97) and ((ord($ref[$i]))<=122))
        or (((
ord($ref[$i]))>=65) and ((ord($ref[$i]))<=90)))
             {
                
$resul $resul.$ref[$i];
             }
        else
             {

              switch (
$ref[$i])
                    {
                    case 
"*"$resul == $resul."%";
                    case 
"?"$resul == $resul."_";
                    default:;
                    }
               }
     }

$ref_num2 strtoupper($resul);

return 
$ref_num2;
}

//******************************************************************************
//TECH_INFO
//******************************************************************************
function TECH_INFO($ref_without_blanks,$id_sup)
{

if ((
$ref_without_blanks == '') or ($id_sup == ''))
    {
        echo 
"INCORRECT URL PARAMETERS";
    }
else
    {

    
$query "SELECT ti.ref_num, sp.supplier_name, tt.ref_type, tt.xml_tag, ti.svalue
              FROM technical_items tt, suppliers sp, technical_inf ti, main_reference mr
              WHERE tt.xml_tag <>''
              AND mr.ref_without_blanks='
$ref_without_blanks'
              AND ti.ref_num=mr.ref_with_blanks
              AND ti.id_sup=
$id_sup
              AND ti.tech_id=tt.tech_id
              AND ti.id_sup=sp.id_sup"
;

    
$consulta consulta_bd($query);

    
$Ra 0;
    
$Rm 0;
    
$Rc 0;
    
    echo 
"<br>&lt;TECH_INFO&gt;<br>";

    while (
$fila ibase_fetch_object ($consulta)) {
        if (
$fila->REF_TYPE == M) {
            if (
$Rm == 0) {
                echo 
"&lt;REF_NUM&gt;$fila->REF_NUM&lt;/REF_NUM&gt;<br>
                    &nbsp;&lt;SUPPLIER_NAME&gt;
$fila->SUPPLIER_NAME&lt;/SUPPLIER_NAME&gt;<br>
                    &nbsp;&nbsp;&lt;REF_TYPE&gt;
$fila->REF_TYPE&lt;/REF_TYPE&gt;<br>";
                
$Rm++;
            }
            echo 
"&nbsp;&nbsp;&nbsp;&lt;$fila->XML_TAG&gt;$fila->SVALUE&lt;/$fila->XML_TAG&gt;<br>";
        }

        if (
$fila->REF_TYPE == A) {
            if (
$Ra == 0) {
                echo 
"&lt;REF_NUM&gt;$fila->REF_NUM&lt;/REF_NUM&gt;<br>
                    &nbsp;&lt;SUPPLIER_NAME&gt;
$fila->SUPPLIER_NAME&lt;/SUPPLIER_NAME&gt;<br>
                    &nbsp;&nbsp;&lt;REF_TYPE&gt;
$fila->REF_TYPE&lt;/REF_TYPE&gt;<br>";
                
$Ra++;
            }
            echo 
"&nbsp;&nbsp;&nbsp;&lt;$fila->XML_TAG&gt;$fila->SVALUE&lt;/$fila->XML_TAG&gt;<br>";
        }

        if (
$fila->REF_TYPE == C) {
            if (
$Rc == 0) {
                echo 
"&lt;REF_NUM&gt;$fila->REF_NUM&lt;/REF_NUM&gt;<br>
                    &nbsp;&lt;SUPPLIER_NAME&gt;
$fila->SUPPLIER_NAME&lt;/SUPPLIER_NAME&gt;<br>
                    &nbsp;&nbsp;&lt;REF_TYPE&gt;
$fila->REF_TYPE&lt;/REF_TYPE&gt;<br>";
                
$Rc++;
            }
            echo 
"&nbsp;&nbsp;&nbsp;&lt;$fila->XML_TAG&gt;$fila->SVALUE&lt;/$fila->XML_TAG&gt;<br>";
        }
    }
 echo 
"<br>&lt;/TECH_INFO&gt;<br>";
 }
}
//******************************************************************************
//SEARCH_REFS
//******************************************************************************
function SEARCH_REFS($ref_num)
{
if ((
$ref_num == ''))
    {
    echo 
"INCORRECT URL PARAMETERS";
    }
else
    {

    
$query "SELECT sp.supplier_name, mr.ref_with_blanks, mr.id_sup, mr.ref_type
              FROM suppliers sp, main_reference mr LEFT OUTER JOIN spare_items si ON mr.ref_type=si.ref_type
              AND mr.id_part_type=si.id_part_type LEFT OUTER JOIN lang l ON si.lang_id=l.lang_id
              WHERE ((mr.id_sup = sp.id_sup)
              AND (mr.ref_without_blanks like '
$ref_num%')
              AND (sp.activated='Y'))
              AND mr.ref_type IN ('A','M','C')
              AND mr.id_part_type=0
              ORDER BY mr.ref_with_blanks"
;

    echo 
"<br>&lt;SEARCH_REF&gt;<br>";
    
    
$consulta consulta_bd($query);
    while (
$fila ibase_fetch_object ($consulta))
    {
    echo 
"<br>&lt;REF&gt;<br>
          &nbsp;&nbsp;&lt;REF_NUM&gt;
$fila->REF_WITH_BLANKS&lt;REF_NUM&gt;<br>
          &nbsp;&nbsp;&nbsp;&lt;ID_SUP&gt;
$fila->ID_SUP&lt;/ID_SUP&gt;<br>
          &nbsp;&nbsp;&nbsp;&lt;SUPPLIER_NAME&gt;
$fila->SUPPLIER_NAME&lt;/SUPPLIER_NAME&gt;<br>
          &nbsp;&nbsp;&nbsp;&lt;REF_TYPE&gt;
$fila->REF_TYPE&lt;/REF_TYPE&gt;<br>
          &lt;/REF&gt;<br>"
;
    }
    echo 
"<br>&lt;/SEARCH_REF&gt;<br>";
    }
}
?>

Esta es la última que estoy utilizando en estos momentos.


La franja horaria es GMT +2. Ahora son las 10:06:44.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi