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 .

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

报告相同问题?

悬赏问题

  • ¥15 请教某软件缓存Ts文件破解合并mp4的方法
  • ¥15 求小游戏炸弹人中关于敌人的C++代码
  • ¥15 拿到这个服务器最高权限有偿
  • ¥50 来个抓app跳转支付宝转链接的
  • ¥15 remotes安装提示没有description文件
  • ¥15 AttributeError: 'NoneType' object has no attribute 'drop_duplicates'报错
  • ¥15 以下代码,运行结果报错
  • ¥15 Vivado仿真数据出错
  • ¥15 银河麒麟不支持vant等前端框架怎么办?
  • ¥15 vue3的子组件在父页面调用不显示不生效问题