MYSQL解析为XML代码


MYSQL Parse to XML code

由于我缺乏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>

请帮帮我。

修改如下:

$xml .= "<".$config['table_name'].">";

:

$xml .= "<".$config['table_name']." id='".$result_array['id']."'>";