【问题标题】:Combining XML files in php在php中组合XML文件
【发布时间】:2018-07-31 23:44:53
【问题描述】:

我正在获取外部 xml 文件(通过文件交换),并且我能够读取并存储在数据库 (php/mysql) 中。 xml 文件以不同的名称压缩,有时几个文件一起压缩在一个文件夹中

当文件夹只有 1 个 xml 文件时,我可以成功解压并使用

 $path = '/xmlFile'; 
   //the xmlFile names are in this format : xmFile-00001235.xml, 
   //xmlFile-000012390.xml, etc.   only first portions are consistent

   foreach (glob($path.'/xmlFile-*.xml') as $filename) 

  {
  $xml=file_get_contents($filename);    

   }
   //store in database and unlink the xml file

这只有在文件夹有一个xml文件时才有效,因为我在存储后取消链接xml文件,它取消链接所有文件但只存储一个

什么是最好的方法;我正在考虑检查文件夹是否有超过 1 个 xml 并合并 xml 文件?也许一个示例解决方案真的会有所帮助,

示例xml如下

xml1.xml

<sales>
    <row id="000001" saleid="267158" amountSold="2000"  />
    <row id="000001" saleid="267159" amountSold="80.000" />
 </sales>

xml2.xml

  <sales>
    <row id="000001" saleid="267160" amountSold="4000"  />
    <row id="000001" saleid="267161" amountSold="580" />
   </sales>

【问题讨论】:

    标签: php xml merge xml-parsing


    【解决方案1】:

    合并多个文件可以像...

    function mergeFile ( DOMDocument $target, $fileName )    {
        $source = new DOMDocument();
        $source->load($fileName);
    
        foreach ( $source->getElementsByTagName("row") as $row )   {
            $import = $target->importNode($row, true);
            $target->documentElement->appendChild($import);
        }
    }
    
    $target = new DOMDocument();
    $target->loadXML('<?xml version="1.0" encoding="utf-8"?><sales></sales>');
    mergeFile($target, "NewFile.xml");
    mergeFile($target, "NewFile1.xml");
    mergeFile($target, "NewFile2.xml");
    
    $target->save("out2.xml");
    

    这允许您继续将所有文件添加在一起,然后在最后保存它们。

    【讨论】:

      【解决方案2】:

      基于Merge XML files in PHP中的答案

      $doc1 = new DOMDocument();
      $doc1->load('1.xml');
      
      $doc2 = new DOMDocument();
      $doc2->load('2.xml');
      
      // get 'res' element of document 1
      $res1 = $doc1->getElementsByTagName('items')->item(0); //edited res - items
      
      // iterate over 'item' elements of document 2
      $items2 = $doc2->getElementsByTagName('item');
      for ($i = 0; $i < $items2->length; $i ++) {
          $item2 = $items2->item($i);
      
          // import/copy item from document 2 to document 1
          $item1 = $doc1->importNode($item2, true);
      
          // append imported item to document 1 'res' element
          $res1->appendChild($item1);
      
      }
      

      【讨论】:

        猜你喜欢
        • 2012-04-27
        • 2018-07-04
        • 2017-12-10
        • 2018-04-17
        • 2014-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多