php - 将 mySQL 数据库输出为 XML 的简单 PHP 脚本

标签 php mysql

我正在参加 PHP 的初学者类(class),我正在尝试将 mySQL 数据库作为 XML 输出到网页。 数据库名称是fruits,它包含三列:idfruitnamefruitcolor

这是我的代码中的内容,但它没有输出任何内容。我哪里错了?

<?php
require_once "inc/db_connect.php";

if($db){
    echo "<p>Connected to Database Successfully</p>";
} elseif(isset($error)){
    echo "<p>$error</p>";
}

?>

<?php
$sql = "SELECT id, fruitname , fruitcolor from fruits";
$res = mysql_query($sql);

$xml = new XMLWriter();

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

$xml->startElement('fruits');

while ($row = mysql_fetch_assoc($res)) {
    $xml->startElement("id");

    $xml->writeAttribute('id', $row['id']);
    $xml->writeRaw($row['fruitname']);
    $xml->writeRaw($row['fruitcolor']);

    $xml->endElement();
}

$xml->endElement();

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

?>

最佳答案

可能是因为 $xml->openURI("php://output"); 需要是 $xml->openURI("php://stdout");

如果不行,试试我的其他解决方案:

看看XMLWriter::flush

If you opened the writer in memory, this function returns the generated XML buffer, Else, if using URI, this function will write the buffer and return the number of written bytes

尝试将 $xml->openURI("php://output");$xml->openMemory();$xml- 交换>flush();echo $xml->flush();

结果代码:

<?php
require_once "inc/db_connect.php";

if($db){
    echo "<p>Connected to Database Successfully</p>";
} elseif(isset($error)){
    echo "<p>$error</p>";
}

?>

<?php
$sql = "SELECT id, fruitname , fruitcolor from fruits";
$res = mysql_query($sql);

$xml = new XMLWriter();

$xml->openMemory();
$xml->startDocument();
$xml->setIndent(true);

$xml->startElement('fruits');

while ($row = mysql_fetch_assoc($res)) {
    $xml->startElement("id");

    $xml->writeAttribute('id', $row['id']);
    $xml->writeRaw($row['fruitname']);
    $xml->writeRaw($row['fruitcolor']);

    $xml->endElement();
}

$xml->endElement();

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

?>

关于php - 将 mySQL 数据库输出为 XML 的简单 PHP 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25832739/

相关文章:

mysql - 手动增量值如何插入选择?

sql - 如何在 MySQL 中执行 FULL OUTER JOIN?

MySQL max(date) 返回最大日期,但其他字段错误

mysql - SQL - 计数不返回零

PHP 使用 try-catch 进行多个数据库查询

php - SQLite3无缓冲查询

php - 通过 html 表单和 php 将外国 lang 数据插入 mysql db 表

javascript - foreach 循环中的自定义输入数字

javascript - 单击按钮 div 显示 1 x 1(一次一个)

mysql - SQL关于生成新表的问题