生成XML文件并将其保存到磁盘时,收到以下错误消息。我得到“XML文档必须有一个顶级元素”。可能是什么问题呢?我感谢任何帮助。如果我使用
echo sqlToXml($result, "SalesOrder", "sales");
xml数据显示在IE中。但由于某些原因,当我尝试保存它时会抛出错误。
header("content-type:text/xml");
$connection = mysql_connect( $db_host, $db_username, $db_password );
if (!$connection){
die ("Could not connect to the database: <br />". mysql_error());
}
// Select the database
$db_select=mysql_select_db($db_database);
if (!$db_select){
die ("Could not select the database: <br />". mysql_error());
}
$result = mysql_query("SELECT * from table1");
header("Content-Type: application/xml");
$xmlDocument1 = sqlToXml($result, "SalesOrder", "sales");
$filename= 'c:\\xmldoc\\results.xml';
file_put_contents($filename ,$xmlDocument1);
function sqlToXml($queryResult, $rootElementName, $childElementName)
{
$xmlData = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n";
$xmlData .= "<" . $rootElementName . ">";
while($record = mysql_fetch_object($queryResult))
{
$xmlData .= "<" . $childElementName . ">";
for ($i = 0; $i < mysql_num_fields($queryResult); $i++)
{
$fieldName = mysql_field_name($queryResult, $i);
$xmlData .= "<" . $fieldName . ">";
if(!empty($record->$fieldName))
$xmlData .= $record->$fieldName;
else
$xmlData .= "null";
$xmlData .= "</" . $fieldName . ">";
}
$xmlData .= "</" . $childElementName . ">";
}
$xmlData .= "</" . $rootElementName . ">";
}
以下是结果XML。
<?xml version="1.0" encoding="ISO-8859-1" ?>
<SalesOrder>
<Sales>
<SalesOrderNumber>SO43</SalesOrderNumber>
<PurchaseOrderNumber>PO18</PurchaseOrderNumber>
<AccountNumber>3333</AccountNumber>
<OrderDate>2001-07-01</OrderDate>
</Sales>
</SalesOrder>
答案 0 :(得分:1)
您是否错过了sqlToXml-Function中的 return 语句?
}
$xmlData .= "</" . $childElementName . ">";
}
$xmlData .= "</" . $rootElementName . ">";
return $xmlData;
}