donglao7947 2016-11-16 13:57
浏览 40
已采纳

如何在php中删除xml中的额外标记

Here I generate on xml dynamically but in this i got the xml but in the last extra two tags came.

Here My xml

<Main>
<Mainrow>
<code>xxxx</code>
<itemname>AAAAA</itemname>
<qty>5.000</qty>
</Mainrow>
</Main>/Mainrow></Main>

My loop

$stock_txt = '<Main>';
            foreach($results as $key => $datas){
                   $stock_txt .= '<Mainrow>';
                    foreach($datas as $val=>$res){
                        $stock_txt .= '<'.$val.'>'.$res.'</'.$val.'>';
                    }
                        $stock_txt .= '</Mainrow>';
                }
           $stock_txt .= '</Main>';
           $dom->loadXML($stock_txt);
           $dom->save($myFile); // myFile -- my path to save file
           fwrite($fh, $stock_txt);     

how to trim the last

/Mainrow and Main

I tried

substr($stock_txt,-22); but failed to get the XML generation

Thanks in advance

  • 写回答

1条回答 默认 最新

  • doupuxuan5784 2016-11-16 14:42
    关注

    Do not create XML as text, use DOM or XMLWriter methods to create/add the nodes. You load your XML string into DOM and save it. So why not use DOM methods from the start:

    $results = [
      [
        'code' => 'xxxx',
        'itemname'=> 'AAAAA',
        'qty'=> '5.000'
      ]
    ];
    
    $document = new DOMDocument();
    $main = $document->appendChild($document->createElement('Main'));
    foreach ($results as $datas) {
      $row = $main->appendChild($document->createElement('Mainrow'));
      foreach ($datas as $name => $value) {
         $row
           ->appendChild($document->createElement($name))
           ->appendChild($document->createTextNode($value));
      }
    }
    
    $document->formatOutput = TRUE;
    //$document->save($myFile);
    echo $document->saveXml();
    

    Output:

    <?xml version="1.0"?>
    <Main>
      <Mainrow>
        <code>xxxx</code>
        <itemname>AAAAA</itemname>
        <qty>5.000</qty>
      </Mainrow>
    </Main>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加