It'sOK
It'sOK

Reputation: 65

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.

<?php
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");
$stmt->execute();
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!

Upvotes: 0

Views: 3561

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33813

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.

<?php

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

    if( $stmt ){
        $res=$stmt->execute();
        if( $res ){

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

            while( $rs=$stmt->fetch( PDO::FETCH_OBJ ) ){
                $test=$dom->createElement('test');

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

                $root->appendChild( $test );
            }
        }

        $stmt->closeCursor();

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

?>

Upvotes: 1

Related Questions