【问题标题】:How am i able to format XML output correctly我如何能够正确格式化 XML 输出
【发布时间】:2018-03-08 16:36:04
【问题描述】:

我正在尝试使用 PHP 以 XML 格式显示数据库的内容。我能够显示数据,但是我无法正确格式化它。任何建议将不胜感激。

我想要达到的输出。

<people>
    <person>
        <id>111</id>
        <first_name>sara</first_name>
        <last_name>smith</last_name>
        <email>ssmith@mail.com</email >
    </person >
</people>

目前的输出是这样的:

我的 PHP 代码

<?php 
  // Create con
    $con=mysqli_connect("HOST","USERNAME","PASSWORD","DB");

    // Check connection
    if (mysqli_connect_errno())
    {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    //get student ID from URL
    $STU_ID = $_GET['id'];

    $sql = "SELECT * FROM table";
    $res = mysqli_query($con, $sql);

    $xml = new XMLWriter();

    $xml->openURI("php://output");
    $xml->startDocument();
    $xml->setIndent(true);

    $xml->startElement('people');

    while ($row = mysqli_fetch_assoc($res)) {
      $xml->startElement("person");

      $xml->writeElement("id", $row['id']);
      $xml->writeElement("first_name", $row['first_name']);
      $xml->writeElement("last_name", $row['last_name']);
       $xml->writeElement("email", $row['email']);
      $xml->writeRaw($row['person']);

      $xml->endElement();
    }

    $xml->endElement();

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

     mysqli_free_result($res); 
    // Close connections
    mysqli_close($con);
?>

【问题讨论】:

  • 你当前的输出是什么?
  • 添加了当前输出的图像。谢谢
  • 在阅读格式化版本时,是否需要放在其他页面中?还是只会在只有 XML 的页面上看到它?
  • 另一种解决方案是将 header("Content-type: text/xml"); 放在脚本的顶部,告诉浏览器它读取的内容是 XML,以便它为您设置格式。
  • @JoshTaylor!谢谢你,非常感谢。

标签: php mysql xml database mysqli


【解决方案1】:

根据上面的 cmets...

在浏览器中查看 html 或 xml 时,不会呈现尖括号内的未知标签。您可以使用浏览器的查看源代码选项查看它们。

正如 Josh Taylor 在评论中指出的那样,您应该能够输出

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

但请参阅http://php.net/manual/en/function.header.php 中的此注释:

请记住,必须在发送任何实际输出之前调用 header(),无论是通过普通 HTML 标记、文件中的空白行还是通过 PHP。

【讨论】:

  • "默认情况下,尖括号内的标签是隐藏的" - 不是隐藏而是渲染。 HTML/XML 被呈现为 HTML 并且未知标签被忽略。如果您有一个在 HTML 中具有可见效果的标签,则该效果也将在此处可见。
猜你喜欢
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 2020-02-22
  • 2020-06-14
  • 1970-01-01
相关资源
最近更新 更多