【发布时间】:2015-08-28 09:32:57
【问题描述】:
下面提到的代码能够从数据库中获取数据,输出也是 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:stackoverflow.com/questions/143122/…
-
嗨,桑德比。感谢您的回复。我是 xml 新手。你能帮忙在哪里更改代码吗?但我无法与你发送的链接联系起来。
-
看看我的回答,我觉得这样就可以了
标签: php xml xml-parsing