下面提到的代碼能夠從數據庫中獲取數據,輸出也是XML格式,但是我想要的順序不正確。不正確的XML格式輸出
<?php
$config['mysql_host'] = "localhost";
$config['mysql_user'] = "market";
$config['mysql_pass'] = "12345";
$config['db_name'] = "marketing";
$config['table_name'] = "data";
$root = customers;
//connect to host
mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']);
//select database
@mysql_select_db($config['db_name']) or die("Unable to select database");
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = $root;
$xml .= "<$root_element>";
//select all items in table
$sql = "SELECT * FROM ".$config['table_name'];
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result)>0)
{
while($result_array = mysql_fetch_assoc($result))
{
$xml .= "<".$config['table_name'].">";
//loop through each key,value pair in row
foreach($result_array as $key => $value)
{
//$key holds the table column name
$xml .= "<$key>";
//embed the SQL data in a CDATA element to avoid XML entity issues
$xml.=$value;
//and close the element
$xml .= "</$key>";
}
$xml.="</".$config['table_name'].">";
}
}
//close the root element
$xml .= "</$root_element>";
//send the xml header to the browser
header ("Content-Type:text/xml");
//output the XML data
echo $xml;
?>
電流輸出:
<customers>
<data>
<customer>111</customer>
<openingbal>111</openingbal>
<pandl>11</pandl>
<currentbal>111</currentbal>
<time>2015-08-28 04:07:21</time>
</data>
<data>
<customer>111</customer>
<openingbal>111</openingbal>
<pandl>11</pandl>
<currentbal>111</currentbal>
<time>2015-08-28 04:07:21</time>
</data>
</customers>
但我想下面其中id = "something">
但上面的代碼不產生相同的結果輸出。
<Customers>
<Customer ID ="111">
<openingbal>111</openingbal>
<pandl>11</pandl>
<currentbal>111</currentbal>
<time>2015-08-14 03:14:30</time>
</Customer>
<Customer Id = "111">
<openingbal>111</openingbal>
<pandl>11</pandl>
<currentbal>111</currentbal>
<time>2015-08-14 03:14:30</time>
</Customer>
</Customers>
嘗試的SimpleXML:http://stackoverflow.com/questions/143122/using-simplexml-to-create-an-xml-object-from-scratch – sanderbee
喜sanderbee。感謝您的迴應。我是新來的XML。你能幫助你在哪裏改變代碼。但我無法與您發送的鏈接相關聯。 –
看看我的答案,我認爲這將做伎倆 – sanderbee