由于我缺乏PHP知识,我在使用php将mysql转换为xml时遇到了一些问题。 我从位于http://www.mightywebdeveloper.com/coding/mysql-to-xml-php/
的网站获取此代码<?php
header('Access-Control-Allow-Origin: *');
$oid= $_GET['oid'];
//database configuration
$config['mysql_host'] = "localhost";
$config['mysql_user'] = "thisisuser";
$config['mysql_pass'] = "thisispass";
$config['db_name'] = "mydb";
$config['table_name'] = "mail";
//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 = $config['table_name']."s"; //fruits
$xml .= "<$root_element>";
//select all items in table
$sql = "SELECT * FROM mail WHERE oid='".$oid."' ORDER BY id ";
//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;
?>
经过一些编辑后,它工作正常,输出就像这样。
<mails>
<mail>
<id>101221</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
<mail>
<id>101222</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
</mails>
我的问题是喜欢在邮件标签旁边显示数组计数,类似于
<mails>
<mail id="1"> <-fetched array number?
<id>101221</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
<mail id="2">
<id>101222</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
</mails>
请帮帮我。
答案 0 :(得分:1)
改变这个:
$xml .= "<".$config['table_name'].">";
对此:
$xml .= "<".$config['table_name']." id='".$result_array['id']."'>";