【问题标题】:how to display data as xml structure in browser [duplicate]如何在浏览器中将数据显示为xml结构[重复]
【发布时间】:2011-12-23 16:29:50
【问题描述】:

我正在尝试在浏览器中显示 xml。我已经创建了一个类似的 xml

$query2 = "SELECT * FROM user where user_id = 7";
$dbresult = mysqli_query($dbcon,$query2) or die('query error...');

$doc = new DomDocument('1.0');
 $doc->formatOutput = true; 

$root = $doc->createElement('root');
$root = $doc->appendChild($root);

while($row = mysqli_fetch_array($dbresult)) {

  $userId = $doc->createElement('UserId');
  $userId = $root->appendChild($userId);
   $value = $doc->createTextNode($row[0]);
  $value = $userId->appendChild($value);

   $psw = $doc->createElement('Password');
  $psw = $root->appendChild($psw);
   $value = $doc->createTextNode($row[2]);
  $value = $psw->appendChild($value);


} 
echo $doc->saveXML();
$doc->save("test.xml"); 

它只显示类似的数据

7 pwd123

但我想要这样的数据

<xml>
   <root>
     <userId>7</userId>
     <password>pwd123</password>
   </root>
</xml>

为此该怎么办? 谢谢

【问题讨论】:

    标签: php xml


    【解决方案1】:

    您的脚本不会 set Content-type header 和 php 发送 default content-type header 通常是 Content-type: text/html
    因此,客户端假定数据是一个 html 文档并对其进行解析和显示。
    如果客户端/浏览器不“知道”您的文档包含的标签/元素(并且上下文很重要)http://www.w3.org/TR/html401/appendix/notes.html#notes-invalid-docs 适用。

    如果您“告诉”客户端输出是一个 xml 文档,它将/可以/应该相应地显示它。

    if ( headers_sent() ) {
        // can't set the content-type after output has been sent to the client
        die('error');
    }
    else {
        header('Content-type: text/xml'); // see http://en.wikipedia.org/wiki/XML_and_MIME
        echo $doc->saveXML();   
    }
    

    【讨论】:

      【解决方案2】:

      更改标题内容类型 text/xml

      header('Content-type: text/xml');
      $doc->saveXML();
      

      更多详情请咨询http://www.w3schools.com/xml/xml_server.asp

      【讨论】:

        【解决方案3】:

        使用右键->显示源代码命令

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-18
          • 2020-01-15
          • 2013-02-26
          • 2014-10-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多