使用PHP和Mysql生成XML页面

时间:2013-11-19 10:12:07

标签: php mysql xml

我想生成类似于此

的XML文件
<mainnode>
<node1  name="aaa">
       <subnode   name1="39576" /> 1<subnode/>
       <subnode><subnode/>
       <subnode/>
</node1>

<node1  name="bbb">
       <subnode   name1="39576" /> 1<subnode/>
       <subnode><subnode/>
       <subnode/>
</node1>

<node1  name="aaa">
       <subnode   name1="39576" /> 1<subnode/>
       <subnode><subnode/>
       <subnode/>
</node1>

<node1  name="ccc">
       <subnode   name1="39576" /> 1<subnode/>
       <subnode><subnode/>
       <subnode/>
</node1>

<node1  name="ccc">
       <subnode   name1="39576" /> 1<subnode/>
       <subnode><subnode/>
       <subnode/>
</node1>

<node1  name="aaa">
       <subnode   name1="39576" /> 1<subnode/>
       <subnode><subnode/>
       <subnode/>
</node1>

<node1  name="ddd">
       <subnode   name1="66666" />
</node1>

mainnode和第一个node1将是用户定义的nodename,子节点将是数据库字段名称的名称

node1和subnode的属性也来自数据库字段

帮我创建php文件(xml格式化)

这是我的PHP代码

<?php
include('config.php');
header('content-type:text/xml');          
$table_id = 'rooms';
$query = "SELECT * FROM devices";
$dbresult = mysql_query($query);

$doc = new DomDocument('1.0');

$root = $doc->createElement('home_automation');
$root = $doc->appendChild($root);

$num = mysql_num_rows($dbresult);
$root->setAttribute('total',$num);

if($num)
{
$i=1;
while($row = mysql_fetch_assoc($dbresult)) 
    {

  $occ = $doc->createElement($table_id);

  $occ = $root->appendChild($occ);


  foreach ($row as $fieldname => $fieldvalue) 
      {
      $child = $doc->createElement($fieldname);
      $child = $occ->appendChild($child);

      if($fieldname == 'img')
          $value = $doc->createTextNode("http://e-megha.electronicbits.in/img/icon/".$fieldvalue);
      else $value = $doc->createTextNode($fieldvalue);
      $value = $child->appendChild($value);


      } 
  $i++;
} 
}
else
{
}

$xml_string = $doc->saveXML();
echo $xml_string;
?> 

现在XML看起来像

enter image description here

0 个答案:

没有答案