我在将数据插入MySQL数据库时使用mysql_real_escape_string函数。我正在
“结束标记'test_field'与开始标记'结束'不匹配。错误 处理资源“
生成XML时。它看起来像特殊字符或小于或大于导致此问题的符号。这是我的代码。如果有任何建议,请告诉我。
这是PHP代码。
$result = mysql_query("SELECT * from table1");
header("Content-Type: application/xml");
echo sqlToXml($result, "SalesOrder", "sales");
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 . ">";
}
$detail = mysql_query("SELECT * from table2 WHERE salesordernumber = '".$record->SalesOrderNumber."'");
while ($row = mysql_fetch_object($detail)) {
$xmlData .= "<Details>";
$xmlData .= "<SalesOrderDetailID>" . $row->SalesOrderDetailID . "</SalesOrderDetailID>";
$xmlData .= "<Name>" . $row->Name . "</Name>";
$xmlData .= "<CarrierTrackingNumber>" . $row->CarrierTrackingNumber . "</CarrierTrackingNumber>";
$xmlData .= "</Details>";
}
$xmlData .= "</" . $childElementName . ">";
}
$xmlData .= "</" . $rootElementName . ">";
}
答案 0 :(得分:0)
我建议使用PHP XMLWriter来生成XML。您可以使用它轻松生成有效的XML文件,并且它更具可读性:
function sqlToXml($queryResult, $rootElementName, $childElementName) {
$w = new XMLWriter();
$w->openMemory();
$w->setIndent(true);
// use tabs as indents
$w->setIndentString(" ");
$w->startDocument("1.0", 'ISO-8859-1');
$w->startElement($rootElementName);
while($record = mysql_fetch_object($queryResult)) {
$w->startElement($childElementName);
for ($i = 0; $i < mysql_num_fields($queryResult); $i++) {
$fieldName = mysql_field_name($queryResult, $i);
$w->startElement($fieldName);
if(!empty($record->$fieldName)) {
$w->writeCData($record->$fieldName);
}
else {
$w->writeCData("null");
}
$w->endElement(); // $fieldName
}
$w->endElement(); // $childElementName
}
$w->endElement(); // $rootElementName
$w->endDocument();
return $w->outputMemory();
}