【发布时间】: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