Oook Oook - 8 days ago 3
MySQL Question

PHP XML error - extra content at the end of the document

I have the PHP code below, intended to create an XML document from 3 columns and multiple rows in an MySQL database. I am getting the following error message:

This page contains the following errors:

error on line 8 at column 11: Extra content at the end of the document
Below is a rendering of the page up to the first error.

-Some correct output as text.-

It drives me crazy, I have added and removed XML stuff in the code but nothing helps.

header('Content-type: text/xml');

$xmlout = "<?xml version=\"1.0\" ?>\n";
$xmlout .= "<TestXML>\n";

$db = new PDO('mysql:host=localhost;dbname=hidden','hidden','hidden');
$stmt = $db->prepare("SELECT * FROM testDB");
while($row = $stmt->fetch()){
$xmlout .= "\t<test>\n";
$xmlout .= "\t\t<one>".$row['one']."</one>\n";
$xmlout .= "\t\t<two>".$row['two']."</two>\n";
$xmlout .= "\t\t<three>".$row['date1']."</three>\n";
$xmlout .= "\t</test>\n";

$xmlout .= "</TestXML>";
echo $xmlout;

Help is very appreciated!


I would suggest using DOMDocument for the generation of XML rather than string concatenation. Depending upon the expected content you might also with to use CDATA sections to the XML - quite a simple modification to the code to allow that.


    $sql='select * from `testdb`';
    $db=new PDO('mysql:host=localhost;dbname=hidden','hidden','hidden');
    $stmt=$db->prepare( $sql );

    if( $stmt ){
        if( $res ){

            $dom=new DOMDocument;
            $dom->appendChild( $root );

            while( $rs=$stmt->fetch( PDO::FETCH_OBJ ) ){

                $test->appendChild( $dom->createElement('one', $rs->one ) );
                $test->appendChild( $dom->createElement('two', $rs->two ) );
                $test->appendChild( $dom->createElement('three', $rs->three ) );

                $root->appendChild( $test );


        header('Content-Type: text/xml');
        echo $dom->saveXML();