我正在尝试从父子表生成XML。这是我想要实现的XML格式。 PHP代码仅适用于一个表。我不知道如何从子表生成XML。我感谢任何帮助。
<SalesOrder>
<Sales>
<SalesOrderNumber>SO43660</SalesOrderNumber>
<PurchaseOrderNumber>PO18850127500</PurchaseOrderNumber>
<AccountNumber>3333</AccountNumber>
<OrderDate>2001-07-01</OrderDate>
<Details>
<SalesOrderDetailID>13</SalesOrderDetailID>
<Name>Road-650 Red, 44</Name>
<CarrierTrackingNumber>6431-4D57-83</CarrierTrackingNumber>
</Details>
<Details>
<SalesOrderDetailID>14</SalesOrderDetailID>
<Name>Road-450 Red, 52</Name>
<CarrierTrackingNumber>6431-4D57-83</CarrierTrackingNumber>
</Details>
</Sales>
</SalesOrder>
这是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 . ">";
}
$xmlData .= "</" . $childElementName . ">";
}
$xmlData .= "</" . $rootElementName . ">";
}
这是架构。
SalesOrder Table SalesOrderDetail
---------------- ------------------
SalesOrderNumber Varchar(20) SalesOrderDetailID INT
PurchaseOrderNumber Varchar(20) SalesOrderNumber Varchar(20)
AccountNumber Varchar(20) Name Varchar(30)
OrderDate Date CarrierTrackingNumber Varchar(30)
答案 0 :(得分:0)
在这两行之间:
}
$xmlData .= "</" . $childElementName . ">";
添加以下内容:
$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>";
}
第一行运行查询以从第二个表中获取数据
第二行是返回记录的循环 - 使$row
成为每条记录的对象。 while循环中的所有内容都会添加到XML字符串($xmlData
)
指向mysql_fetch_object文档的链接