Foros del Web » Programando para Internet » PHP »

Problema con saltos de linea de XML en PHP

Estas en el tema de Problema con saltos de linea de XML en PHP en el foro de PHP en Foros del Web. Saludos, esta es mi primera intervención en este foro, aunque llevo ya tiempo acudiendo a él, y siempre me ha resultado de gran ayuda . ...
  #1 (permalink)  
Antiguo 07/02/2009, 09:46
 
Fecha de Ingreso: febrero-2009
Mensajes: 8
Antigüedad: 15 años, 2 meses
Puntos: 0
Pregunta Problema con saltos de linea de XML en PHP

Saludos, esta es mi primera intervención en este foro, aunque llevo ya tiempo acudiendo a él, y siempre me ha resultado de gran ayuda .

Llevo mucho tiempo buscando una solución para este problema y no la he podido encontrar.

Intento sacar el contenido de un archivo XML para mostrarlo en un web. En concreto, quiero obtener letras de canciones a través de la API de lyricwiki.org.

Llevo poco tiempo programando en PHP, por eso busqué algun código ya realizado para obtener los datos de XML, y lo adapté a mis necesidades:

Código PHP:
<?php
$myFile
="h t t p : / / lyricwiki . o r g /api.php?artist=$artista&song=$nom&fmt=xml";
$theData file_get_contents($myFile);
$xml=( xml2array($theData));

print 
'<p>';
print(
"\n".$xml['LyricsResult']['lyrics']['value']);
print 
'</p>';
$xml ereg_replace("<br>","\r",$acti);

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$parserXML_OPTION_CASE_FOLDING);
    
xml_parser_set_option$parserXML_OPTION_SKIP_WHITE);
    
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
        
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($tagarray_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);
}
El XML de donde obtiene los datos, es
Código PHP:
 h t t p : / / lyricwiki o r g /api.php?artist=$artista&song=$nom&fmt=xml 
Dentro de la dirección estan las variables $artista y $nom, que se declaran desde la URL (Por ejemplo "mipagina.php?artista=Coldplay&nom=Clocks", lo carga como:

h t t p : / / lyricwiki . o r g /api.php?artist=Coldplay&song=Clocks&fmt=xml

Hasta aquí, todo va bien. El problema es que el código XML tiene saltos de línea, y al cargar los datos por php se pierden.

¿Alguien conoce alguna solución?

NOTA: He espaciado las direcciones porque el filtro anti-spam no me deja incluirlas.

Última edición por vicent34; 07/02/2009 a las 12:54
  #2 (permalink)  
Antiguo 07/02/2009, 15:55
okram
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Problema con saltos de linea de XML en PHP

Usa nlsbr() antes de imprimir el contenido del xml.

  #3 (permalink)  
Antiguo 09/02/2009, 03:25
 
Fecha de Ingreso: febrero-2009
Mensajes: 8
Antigüedad: 15 años, 2 meses
Puntos: 0
Respuesta: Problema con saltos de linea de XML en PHP

Cita:
Iniciado por okram Ver Mensaje
Usa nlsbr() antes de imprimir el contenido del xml.
Gracias, pero acabo de probar poniendo
Código PHP:
print nl2br($xml['LyricsResult']['lyrics']['value']) 
y el problema persiste! Es decir, que si el texto del xml es
Código:
Lorem ipsum dolor sit amet
Consectetur adipiscing elit
El me devuelve:
Lorem ipsum dolor sit ametConsectetur adipiscing elit
  #4 (permalink)  
Antiguo 09/02/2009, 07:58
okram
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Problema con saltos de linea de XML en PHP

En el código fuente generado que ves?

  #5 (permalink)  
Antiguo 09/02/2009, 10:51
 
Fecha de Ingreso: febrero-2009
Mensajes: 8
Antigüedad: 15 años, 2 meses
Puntos: 0
Respuesta: Problema con saltos de linea de XML en PHP

Cita:
Iniciado por okram Ver Mensaje
En el código fuente generado que ves?

En el código fuente solo aparece el texto, sin ninguna etiqueta más. Es decir, si en el ejemplo de antes el XML tenia

Código:
Lorem ipsum dolor sit amet
Consectetur adipiscing elit
El código fuente muestra:

Código HTML:
Lorem ipsum dolor sit ametConsectetur adipiscing elit
  #6 (permalink)  
Antiguo 09/02/2009, 16:01
okram
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Problema con saltos de linea de XML en PHP

Si en el fuente te aparece sin saltos de línea, quiere decir que tu xml te está devolviendo los datos así, planos, o que al momento de analizar el xml (con tu xml2array()) estás omitiendo los saltos de línea.

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:11.