Foros del Web » Programando para Internet » PHP »

Edicion de un XML desde un PHP - ayuda u.u

Estas en el tema de Edicion de un XML desde un PHP - ayuda u.u en el foro de PHP en Foros del Web. Un saludo a todos, continuando con la edicion de los archivos XML desde un php, tengo problemas al mostrar las variables del xml, les muestro ...
  #1 (permalink)  
Antiguo 17/04/2008, 12:33
Avatar de dsintekzombie  
Fecha de Ingreso: abril-2008
Mensajes: 14
Antigüedad: 16 años
Puntos: 0
Pregunta Edicion de un XML desde un PHP - ayuda u.u

Un saludo a todos, continuando con la edicion de los archivos XML desde un php, tengo problemas al mostrar las variables del xml, les muestro los codigo fuente para realizar esto:

Nuestra pagina donde podemos editar el xml:

pagina1.php

Código PHP:
<?php
require dirname(__FILE__).'functions.php';

// get menu.xml file
$p =& new xmlParser();
$p->parse('pagina1.xml');
$settings $p->output[0]['child'];


?>

        <h1>Pagina 1</h1>
          <hr />
          <table width="700" border="0">
          <tr>
            <td width="294" valign="top"><?php
  $xml 
"";
  
$f fopen'pagina1.xml''r' );
  while( 
$data fread$f4096 ) ) { $xml .= $data; }
  
fclose$f );
  
  
preg_match_all"/\<news\>(.*?)\<\/news\>/s"
  
$xml$bookblocks );
  
  foreach( 
$bookblocks[1] as $block )
  {
  
preg_match_all"/\<header\>(.*?)\<\/header\>/"
  
$block$header );
  
preg_match_all"/\<content\>(.*?)\<\/content\>/"
  
$block$content );
  
preg_match_all"/\<author\>(.*?)\<\/author\>/"
  
$block$author );
  
preg_match_all"/\<comment\>(.*?)\<\/comment\>/"
  
$block$comment );
  echo( 
$header[1][0]." \n ".$content[1][0]." \n ".$author[1][0]." \n ".$comment[1][0]."\n" );
  }
  
?>&nbsp;</td>
            <td width="396"><form action="save_page1.php" method="post">
              <p>&nbsp;</p>
              <table width="227" border="0" cellpadding="0" cellspacing="0">
                <tr>
                  <td width="227"><p>Titulo:<br />
                          <input name="header" type="text" id="header"  value="<?php echo utf8_decode($settings[0]['content']); ?>" />
                    </p>
                      <p>Contenido:<br />
                          <textarea name="content" cols="35" rows="10" id="content"><?php echo utf8_decode($settings[1]['content']); ?></textarea>
                      </p>
                    <p>Autor:<br />
                          <input name="author" type="text" id="author" value="<?php echo utf8_decode($settings[2]['content']); ?>" />
                      </p>
                    <p>Comentarios:<br />
                          <input name="comment" type="text" id="comment" value="<?php echo utf8_decode($settings[3]['content']); ?>" />
                      </p>
                    <p>
                        <input type="submit" value="guardar cambios"/>
                    </p></td>
                </tr>
              </table>
              <p>&nbsp;</p>
              <p>&nbsp;</p>
            </form></td>
          </tr>
        </table>
Aqui esta el php, que guarda nuestros cambios:

save_page1.php

Código PHP:
<?php
//check user

require dirname(__FILE__).'functions.php';

//get the post variables
$header utf8_encode($_POST['header']);
$content utf8_encode($_POST['content']);
$author utf8_encode($_POST['author']);
$comment utf8_encode($_POST['comment']);

$filename realpath("pagina1.xml");

//make xml
$xml "<news>
    <header>$header</header>
    <content>$content</content>
    <comment>$author</comment>
    <author>$comment</author>
</news>"
;

/*
<news>
    <header>$border</header>
    <content>$border</content>
    <comment>$border</comment>
    <author>$border</author>
</news>
*/

// make sure xml exists and is writable
if (is_writable($filename)) {
    
//open the file
   
if (!$handle fopen($filename'wb')) {
         
error("Cannot open file");
         exit;
   }

   
// writing new xml
   
if (fwrite($handle$xml) === FALSE) {
       
error("Cannot write to file");
       exit;
   }
   
   
fclose($handle);

} else {
   
error("settings.xml does not seem to be writable. Check that you have changed its CHMOD settings to 777.");
}

//go back to settings page
header("Location:pagina1.php");
?>
Para salvar, me pide este archivo:

functions.php

Código PHP:
<?php
//closes a window. Used for opened windows servering
//as data entry screens.
function close($msg) {
    
?>
    <html>
    <head>
    <script language="JavaScript" type="text/javascript">
    <!--
        alert("<?=$msg?>");
        window.close();
    //-->
    </script>
    </head>
    <body>
    </body>
    </html>
    
    <?php
    
exit;
}
//error function in case something goes wrong
function error($msg) {
    
?>
    <html>
    <head>
    <script language="JavaScript" type="text/javascript">
    <!--
        alert("<?=$msg?>");
        history.back();
    //-->
    </script>
    </head>
    <body>
    </body>
    </html>
    <?php
    
exit;
}


class 
xmlParser{

   var 
$xml_obj null;
   var 
$output = array();
  
   function 
xmlParser(){
     
       
$this->xml_obj xml_parser_create();
       
xml_set_object($this->xml_obj,$this);
       
xml_set_character_data_handler($this->xml_obj'dataHandler');  
       
xml_set_element_handler($this->xml_obj"startHandler""endHandler");
  
   } 
  
   function 
parse($path){
     
       if (!(
$fp fopen($path"r"))) {
           die(
"Cannot open XML data file: $path");
           return 
false;
       }
     
       while (
$data fread($fp4096)) {
           if (!
xml_parse($this->xml_obj$datafeof($fp))) {
               die(
sprintf("XML error: %s at line %d",
               
xml_error_string(xml_get_error_code($this->xml_obj)),
               
xml_get_current_line_number($this->xml_obj)));
               
xml_parser_free($this->xml_obj);
           }
       }
     
       return 
true;
   }

   function 
startHandler($parser$name$attribs){
       
$_content = array('name' => $name);
       if(!empty(
$attribs))
         
$_content['attrs'] = $attribs;
       
array_push($this->output$_content);
   }

   function 
dataHandler($parser$data){
       if(!empty(
$data)) {
           
$_output_idx count($this->output) - 1;
           
$this->output[$_output_idx]['content'] = $data;
       }
   }

   function 
endHandler($parser$name){
       if(
count($this->output) > 1) {
           
$_data array_pop($this->output);
           
$_output_idx count($this->output) - 1;
           
$this->output[$_output_idx]['child'][] = $_data;
       }      
   }

}

function 
rmdirr($dirname)
{
    
// Sanity check
    
if (!file_exists($dirname)) {
        return 
false;
    }
 
    
// Simple delete for a file
    
if (is_file($dirname)) {
        return 
unlink($dirname);
    }
 
    
// Loop through the folder
    
$dir dir($dirname);
    while (
false !== $entry $dir->read()) {
        
// Skip pointers
        
if ($entry == '.' || $entry == '..') {
            continue;
        }
 
        
// Recurse
        
rmdirr("$dirname/$entry");
    }
 
    
// Clean up
    
$dir->close();
    return 
rmdir($dirname);
}
?>
Y finalmente el XML:

pagina.xml

Código PHP:
<news>
    <
header>Don Quijote</header>
    <
content>Empieza la historia...</content>
    <
comment>Primer Capitulo</comment>
    <
author>damian trejo</author>
</
news
Ok, despues de tantos codigos, todos funcionan correctamente, el xml se guarda bien y al mostrarlo en flash tambien, acepta los famosos acentos y las ñ que tanto problema nos ocasionan...

El problema de todo, (creo que me excedi de informacion....) es cuando abro pagina1.php, en los campos que me muestran los datos del xml, solamente me muestra a partir del ultimo acento, por ejemplo si pongo: "hola, necesito tener información de un libro", solamente me aparece: "ón de un libro".



Creo que el problema viene de este codigo que aparece en functions:

Código PHP:
function endHandler($parser$name){
       if(
count($this->output) > 1) {
           
$_data array_pop($this->output);
           
$_output_idx count($this->output) - 1;
           
$this->output[$_output_idx]['child'][] = $_data;
       } 
Por favor si pueden ayudar a resolver esto... les debo una¡¡

Gracias por todo¡¡
  #2 (permalink)  
Antiguo 17/04/2008, 12:40
Avatar de dsintekzombie  
Fecha de Ingreso: abril-2008
Mensajes: 14
Antigüedad: 16 años
Puntos: 0
Re: Edicion de un XML desde un PHP - ayuda u.u

Originalmente no venian con los utf8_encode y utf8_decode, eso se los agregue para que nos acepte acentos y las ñ
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 05:19.