用php添加数字到fetched数组

时间:2015-06-10 14:24:29

标签: php mysql xml

我在解析的xml输出上为fetched数组添加编号时遇到了一些问题。我从位于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>1011</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? I dont know how to add this.
        <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>

请指导我。

1 个答案:

答案 0 :(得分:0)

$mail = 1;   // write this before loop

然后代替$xml .= "<$key>";

$xml .= ($key == 'mail' ? "<$key id=\"".$mail++."\">" : "<$key>");