douyi6168 2015-09-15 12:48
浏览 57
已采纳

使用DOM编写XML文件

I am trying to get data from database and write it to xml file using DOM.

$doc = new DomDocument('1.0', 'UTF-8');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;

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

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

while($result_array = mysqli_fetch_assoc($result)) 
{
    $cms_block = $doc->createElement('cms_block');

    foreach($result_array as $fieldname => $fieldvalue)
    {
        /*This is part that is not working*/

        $key = $doc->createElement($fieldname);
        $cms_block->appendChild($key);
        $value = $doc->createTextNode($fieldvalue);
        $key->appendChild($value);          
    }

    $stores = $doc->createElement('stores');
    $cms_block->appendChild($stores);

    $item = $doc->createElement('item');
    $stores->appendChild($item);

    $itemvalue = $doc->createTextNode('0');
    $item->appendChild($itemvalue); 

    $blocks->appendChild($cms_block);       
}

The above code works and mostly does what I need it to do but it fails within foreach loop and the elements and value that I am trying to add within foreach does not work.

Example of $result_array = mysqli_fetch_assoc($result)

Array ( [title] => Footer Links [identifier] => footer_links [is_active] => 1 ) 

Array ( [title] => Footer Links [identifier] => footer_links [is_active] => 1 )

It would really help me if someone can tell me what I am doing wrong within foreach loop which is not adding the data that I am getting from database to the xml file please.

  • 写回答

1条回答 默认 最新

  • duanlang0025 2015-09-15 12:54
    关注

    Try this to add data from your $results_array

    $cms_block->appendChild($doc->createElement($fieldname, $fieldvalue));
    

    UPDATE Move $blocks->appendChild($cms_block); to the end of your while loop .

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料