XML解析错误:文档元素后面有垃圾


XML Parsing Error: junk after document element

我想从数据库中创建一个xml文件,然后将该文件返回到另一个页面中用于某些ajax。

这是我用来创建xml文件的代码:
<?php
    header("Content-Type:text/XML");
    $connexion = new PDO("mysql:host=localhost;dbname=produits;charset=utf8", 'root', 'toor'); 
    $statement = $connexion->prepare("SELECT * FROM produit"); 
    $statement->execute();
    $resultats = $statement->fetchAll(PDO::FETCH_OBJ);
    $xml_file = new DOMDocument('1.0');
    $root = $xml_file->createElement('produits');

    foreach($resultats as $produit){
        $tel = $xml_file->createElement('telephone');
        $tel->setAttribute('id', $produit->id);
        $marque = $xml_file->createElement('marque');
        $marqueText = $xml_file->createTextNode($produit->marque);
        $marque->appendChild($marqueText);
        $tel->appendChild($marque);
        $model = $xml_file->createElement('model');
        $modelText = $xml_file->createTextNode($produit->model);
        $model->appendChild($modelText);
        $tel->appendChild($model);
        $prix = $xml_file->createElement('prix');
        $prix->setAttribute("devise", "DH");
        $prixText = $xml_file->createTextNode($produit->prix);
        $prix->appendChild($prixText);
        $tel->appendChild($prix);
        $root->appendChild($tel);
    }
    $xml_file->appendChild($root);
    echo $xml_file;
?>

问题是当我打开页面检查xml文件是否创建时,我得到这个错误消息:

XML解析错误:文档元素后的垃圾http://localhost/Ajax/produits/details.php第二行,第二列1: ^

如何解决这个问题?

$xml_file指向DOMDocument实例。DOMDocument没有实现隐式的__toString()转换,因此echo $xml_file;的输出结果如下

Catchable fatal error: Object of class DOMDocument could not be converted to string in ...

和客户端XML解析器抱怨它不是一个有效的XML文档。

你想输出dom的xml表示,你可以通过

echo $xml_file->saveXML();

见http://docs.php.net/domdocument.savexml