Error while generating XML

Asked

Viewed 135 times

1

I made a system in PHP to display XML file, but is giving the following error:

This page contains the following errors: error on line 29 at column 1: Extra content at the end of the Document Below is a Rendering of the page up to the first error.

(The image so you can see that even what’s in the seat he brings me): inserir a descrição da imagem aqui

My index.php file:

<?php

    include("config.php");
    include("conexao.php");

    $sql = 'select id, descricao, margem, custo, estoque from produtos';

    $resultado = mysqli_query(DBConnect(), $sql) or die (mysqli_error(DBConnect()));

    $xml = new DOMDocument('1.0', 'UTF-8');
    $xml->preserveWhiteSpace = false;
    $xml->formatOutput = true;

    $produtos = $xml->createElement('Produtos');

    while($dados = mysqli_fetch_object($resultado))
    {
        $item = $xml->createElement('Item');
        $descricao = $xml->createElement('descricao', $dados->descricao);
        $margem = $xml->createElement('margem', $dados->margem);
        $custo = $xml->createElement('custo', $dados->custo);
        $estoque = $xml->createElement('estoque', $dados->estoque);

        $item->appendChild($descricao);
        $item->appendChild($margem);
        $item->appendChild($custo);
        $item->appendChild($estoque);

        $produtos->appendChild($item);
    }

    $xml->appendChild($produtos);

    header('content-type: text/xml');
    print $xml->saveXML();

?>

<!DOCTYPE html>
<html>

    <head>

        <title> Testando conexão </title>

    </head>

    <body>

        <?php 

            $teste = DBConnect();

            if($teste)
            {
                echo "Conectado com sucesso!";
            }
            else
            {
                echo "Conexão falhou!";
            }

        ?>

    </body>

</html>

My config.php file:

<?php

    define('HOSTNAME', '127.0.0.1');
    define('USERNAME', 'root');
    define('PASSWORD', null);
    define('DATABASE', 'cadastro');
    define('CHARSET' , 'utf8');

?>

My connected.php file:

<?php

    function DBConnect()
    {
        $sql = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DATABASE) or die(mysqli_error());
        mysqli_set_charset($sql, CHARSET) or die(mysqli_error($sql));

        return $sql;
    }

?>

1 answer

1


As the error description itself informs, you are inserting extra alien information after creating XML from the line <!DOCTYPE html>.

To parse XML correctly, remove everything from the line <!DOCTYPE html> down. Removing the line header('content-type: text/xml'); error some, but you will get as a result a normal HTML page (although invalid).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.