dongmei8460 2014-03-19 15:47
浏览 238

XML解析错误:文档元素之后的垃圾

I want to create an xml file from a database, and then to echo this file to use in another page for some ajax.

this is the code I use to create the xml file :

<?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;
?>

The problem is when I open the page to check if the xml file is create, I get this error message :

XML Parsing Error: junk after document element Location: http://localhost/Ajax/produits/details.php Line Number 2, Column 1: ^

How can I solve this problem ?

  • 写回答

1条回答 默认 最新

  • dongnai6973 2015-07-07 09:41
    关注

    $xml_file points to the DOMDocument instance. DOMDocument doesn't implement an implicit __toString() conversion, therefore echo $xml_file; results in output like

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

    and the client-side xml parser complains about it not being a valid xml doc.

    You want to output the xml representation of the dom which you can do e.g. via

    echo $xml_file->saveXML();
    

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

    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)