我正在尝试从我的数据库中获取数据并将其存储在xml文件中,每次运行代码时,我都会在第1行的第2行得到此错误:文档为空。
<?php
header ("Content-Type:text/xml");//Tell browser to expect xml
include ("db_connect.php");
$query = "SELECT * FROM winery";
$result = mysqli_query($connection, $query) or die ("Error in query: $query. ".mysql_error());
//Top of xml file
$_xml = '<?xml version="1.0"?>';
$_xml .="<winerys>";
while($row = mysqli_fetch_array($result)) {
$_xml .="<winery>";
$_xml .="<winery_id>".$row['winery_id']."</winery_id>";
$_xml .="<winery_name>".$row['winery_name']."</winery_name>";
$_xml .="<region_id>".$row['region_id']."</region_id>";
$_xml .="</winery>";
}
$_xml .="</winerys>";
//Parse and create an xml object using the string
$xmlobj=new SimpleXMLElement($_xml);
//And output
print $xmlobj->asXML();
//or we could write to a file
$xmlobj->asXML(winerys.xml);
?>
答案 0 :(得分:0)
假设您正在获取记录集,则以下内容应该可以正常工作,尽管它未经测试。它使用标准DOMDocument
方法生成xml,而不是使用SimpleXMLElement
构建为字符串。它可能不一定像javascript一样真实,但字符串连接有时可能很慢,特别是如果字符串由于大量记录而变得非常大。此外,您的原始代码需要注意的一件事是用于保存xml数据的文件名 - 它显示为不带引号的字符串,因此可能被错误地解释为常量。
<?php
error_reporting( E_ALL );/* to aid debugging */
include ("db_connect.php");
$query = "select * from `winery`;";
$result = mysqli_query( $connection, $query ) or die ('Sorry, there was an error');
/* Create the DOM object */
$dom=new DOMDocument('1.0','utf-8');
/* Add the root node */
$root=$dom->createElement('winerys');
$dom->appendChild( $root );
while( $row = mysqli_fetch_array( $result ) ) {
/* Add a new item / child */
$child=$root->appendChild( $dom->createElement('winery') );
$child->appendChild( $dom->createElement( 'winery_id', $rs->winery_id ) );
/* Use a CDATA section to allow for odd chars */
$name=$dom->createCDATASection( $rs->winery_name );
$winery=$dom->createElement( 'winery_name' );
$winery->appendChild( $name );
$child->appendChild( $winery );
$child->appendChild( $dom->createElement( 'region_id', $rs->region_id ) );
}
/* save and echo */
$xml = $dom->saveXML();
$file = $dom->save('winerys.xml');
header("Content-Type: text/xml");
print_r( $xml );
?>
创建了一个测试数据库表,这似乎按预期工作。