Inserir quebra de linha em XML [RESOLVIDO]

1. Inserir quebra de linha em XML [RESOLVIDO]

Fábio Felix Dias
slack felix

(usa Slackware)

Enviado em 18/07/2008 - 23:43h

Olá,

Estou gerando um arquivo XML com o auxilio do PHP, mais ou menos com o código:

<?php
header("Content-Type:text/html; charset=ISO-8859-1",true);


$xml = simplexml_load_file("teste.xml");
$xml->addChild('tag', '');


file_put_contents('teste.xml', $xml->asXML());
echo $xml->asXML();
?>

O problema é que toda vez que eu insiro uma nova tag elas vão sendo colocadas uma do lado da outra eu queria que ficasse uma embaixo da outra. Ao invés de

<tag></tag><tag></tag><tag></tag>

ficasse

<tag></tag>
<tag></tag>
<tag></tag>

Alguém pode me ajudar?







  


2. Solução

Perfil removido
removido

(usa Nenhuma)

Enviado em 19/07/2008 - 00:17h

Olá! Achei muito interessante a sua dúvida (q se tornou minha dúvida também, heheh. Então encontrei uma função para resolver nosso problema.)

Vou colar na íntegra:

User Contributed Notes
SimpleXMLElement->asXML()
mjijackson at gmail dot com
27-May-2008 09:04
A small improvement on Gary Malcolm's original asPrettyXML() method:

<?php

class XMLElement extends SimpleXMLElement
{

/**
* Outputs this element as pretty XML to increase readability.
*
* @param int $level (optional) The number of spaces to use for
* indentation, defaults to 4
* @return string The XML output
* @access public
*/
public function asPrettyXML($level = 4)
{
// get an array containing each XML element
$xml = explode("\n", preg_replace('/>\s*</', ">\n<", $this->asXML()));

// hold current indentation level
$indent = 0;

// hold the XML segments
$pretty = array();

// shift off opening XML tag if present
if (count($xml) && preg_match('/^<\?\s*xml/', $xml[0])) {
$pretty[] = array_shift($xml);
}

foreach ($xml as $el) {
if (preg_match('/^<([\w])+[^>\/]*>$/U', $el)) {
// opening tag, increase indent
$pretty[] = str_repeat(' ', $indent) . $el;
$indent += $level;
} else {
if (preg_match('/^<\/.+>$/', $el)) {
// closing tag, decrease indent
$indent -= $level;
}
$pretty[] = str_repeat(' ', $indent) . $el;
}
}

return implode("\n", $pretty);
}

}

?>

This method will make sure there is an opening XML tag before automatically shifting the first element off the array, thus preserving the correct indentation level when printing child elements instead of entire documents from the root node. It also allows you to pass the indentation level in as a parameter instead of setting the class variable.



3. Re: Inserir quebra de linha em XML [RESOLVIDO]

Fábio Felix Dias
slack felix

(usa Slackware)

Enviado em 19/07/2008 - 17:50h

Olá bpiero,

Obrigado pela ajuda e fico feliz por minha pergunta ter te ajudado também.

Achei interessante esse código, mesmo eu sendo um tanto leigo em PHP. Fiquei com um pouco de dúvida em como utilizar a função. Você pode me mandar um exemplo dela em ação?

Valeu


4. Re: Inserir quebra de linha em XML [RESOLVIDO]

Fábio Felix Dias
slack felix

(usa Slackware)

Enviado em 20/07/2008 - 17:14h

Eu utilizei a função da seguinte forma:

function asPrettyXML($xml)
{
$level = 4;

/*onde havia o $this eu troquei por $xml*/
}

E no código que eu postei anteriormente, coloquie asPrettyXML no lugar de asXML. Funcionou do jeito que eu queria


5. Oi. Tenho uma outra questão XML

Paulo
henbran

(usa Debian)

Enviado em 30/09/2009 - 10:40h

Consigo até exibir a 1ª coluna de registro de uma consulta SQL, já a 2ª coluna ... dá o seguinte erro:
Erro no processamento de XML: caracteres sem utilidade após um elemento do documento
Posição: http://localhost/rascunhos/bd2.php
Número da linha 2, coluna 1:<NOME_SOLICITANTE>JOSÉ</NOME_SOLICITANTE>
^

O script é:

function exibir($dados) // $dados é 1 matriz multidimensional de uma SELECT SQL c/ PDO
{
$d_xml = "<?xml version='1.0'?>";
foreach ($dados as $lin)
{
foreach ($lin as $key => $value)
{
$d_xml .= "<$key>$value</$key>\n";
// se opto por exibir (interromper o LOOP)
// só esse ciclo do loop, dá certo. Porém ..
}
}
header("Content-type: application/xml");
echo $d_xml; // Aqui já dá o erro
}



  



Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts