XML with PHP “echo” getting error “Extra content at the end of the document”

百般思念 提交于 2019-11-28 02:28:28

Just Right click your output error webpage and VIEW SOURCE CODE you will see the correct error message and line number from your PHP file. You will solve that error in few seconds.

“Extra content at the end of the document”

I would like to solve and understand why this happens.

Why does this happen? This is in short an invalid XML. See the following example:

<xml>
</xml>
This here is extra content at the end of the document

As you can see, nobody would normally create such an XML file. In your case this happens because of a common accident of those programmers who outsmart themselves writing functions to output XML while those functions already exist. They just then forgot to properly output xml and then they are screwed:

$xml = new SimpleXMLElement('<markers/>');

foreach ($databaseResult as $row) 
{
    $marker = $xml->addChild('marker');
    foreach ($row as $key => $value) 
    {
        $marker[$key] = $value;
    }
}

header("Content-type: text/xml");
$xml->asXML('php://output');

This example is using the SimpleXML library. If your database result is very large and you want to stream the data instead, you can take a look at the XMLWriter library:

$writer = new XMLWriter();
$writer->openUri('php://output');

$writer->startDocument();
$writer->startElement('markers');

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

foreach ($databaseResult as $row)
{
    $writer->writeRaw("\n  ");
    $writer->flush();
    $writer->startElement('marker');

    foreach ($row as $key => $value)
    {
        $writer->writeAttribute($key, $value);
    }

    $writer->endElement();
}

$writer->writeRaw("\n");
$writer->endElement();
$writer->flush();

See it in action.

I had same problem and put ' ' around database and it worked.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!