以XML格式输出数据库信息

时间:2015-11-15 20:37:45

标签: php xml

我尝试了4种不同的尝试来获取数据库信息并将其显示为XML。但是,当我单击指定按钮时,它会显示错误:

error on line 2 at column 1: Document is empty

我的连接工作正常,所以这不是问题,但我之前没有尝试过,所以我必须忽视一些事情。

Generatexml.php

<?php
header('Content-type: text/xml');
include 'connection.php';
$query = "SELECT * FROM users"; 
$result = mysqli_query($mysqli_conn, $query) or die ("Error in query: $query. ".mysql_error()); 
//Top of xml file
$_xml .="<people>"; 
    while($row = mysqli_fetch_array($result)) { 
        $_xml .="<person>"; 
        $_xml .="<firstname>".$row['FirstName']."</firstname>"; 
        $_xml .="<lastname>".$row['LastName']."</lastname>"; 
        $_xml .="<username>".$row['Username']."</username>"; 
        $_xml .="<password>".$row['Password']."</password>";
        $_xml .="<id>".$row['P_Id']."</id>";  
        $_xml .="</person>"; 
        } 
        $_xml .="</people>"; 
//Parse and create an xml object using the string
$xmlobj=new SimpleXMLElement($_xml);
//write to an XML file
$xmlobj->asXML('people.xml');
echo $xmlobj->asXML();
?>

编辑:我使用了另一种方法,我能够提取数据库信息并显示它,但它没有以XML格式显示。

<?php
include 'connection.php';

//query the database    
$sqlQuery = "SELECT * FROM users";

//run query
if ($result = mysqli_query($db, $sqlQuery)) {
header('Content-type: text/xml');
echo '<?xml version="1.0" encoding="utf-8"?>';
echo '<results>';
echo '<people>';
    //fetch associative array 
while ($row = mysqli_fetch_assoc($result)) {
echo '<person>';
echo '<firstname>' . $row["FirstName"] . '</firstname>';
echo '<lastname>' . $row["LastName"] . '</lastname>';
echo '</person>';
}
echo '</people>';
}
//close the database connection
$db->close();
echo '</results>';
?>

1 个答案:

答案 0 :(得分:0)

您正在写一个文件。

您没有将该文件的内容发送到浏览器。

echo $xmlonj->asXML();