【问题标题】:How to change a php code to merge any number of XML files如何更改 php 代码以合并任意数量的 XML 文件
【发布时间】:2015-09-14 21:58:56
【问题描述】:

这里的工作代码(我用here)将两个 XML 文件合并为一个。它工作正常,但只有 xml 的 2 个部分。

<?php
$numparts=2;
$filename1='TEST_1.xml';
$filename2='TEST_2.xml';
$doc1 = new DOMDocument();
$doc1->load($filename1);

$doc2 = new DOMDocument();
$doc2->load($filename2);

// 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);
}
$doc1->save('merged.xml'); //edited -added saving into xml file
?>

请帮助更改代码以处理任意数量的片段(存储在变量 $numparts 中)。

【问题讨论】:

  • 到目前为止你做了什么?
  • 只需将它放在一个循环中并合并几个文件。因此,如果您有 3 个文件:将 doc1 与 doc2 合并到 doc12 中,然后将 doc12 与 doc 3 合并,等等。
  • 谢谢你的想法,我试试

标签: php xml merge


【解决方案1】:

首先,使用循环,创建文件名数组,以及您希望合并的相应文档。

$numparts = 3;
// Create an array of $numparts filenames of the xml files you wish to merge
$filenames = array();
for ($i = 1; $i <= $numparts; $i++) {
    $filenames[$i] = 'TEST_' . $i . '.xml';
}
// Create an array of DOM Document objects, one for each xml file
$docs = array();
for ($i = 1; $i <= count($filenames); $i++) {
    $docs[$i] = new DOMDocument();
    $docs[$i]->load($filenames[$i]);
}

然后创建一个循环,遍历除第一个文档之外的所有文档,并将遍历文档(代码示例中的那个)中的项目的循环嵌套在其中。

// get 'res' element of document 1
$doc1 = $docs[1];
 $res1 = $doc1->getElementsByTagName('items')->item(0); //edited res - items
// iterate over all the rest of the documents
for ($i = 2; $i <= count($docs); $i++) {
    $doci = $docs[$i];
    // iterate over 'item' elements of document i
    $itemsi = $doci->getElementsByTagName('item');
    for ($j = 0; $j < $itemsi->length; $j++) {
        $itemi = $itemsi->item($j);
        // import/copy item from document i to document 1
        $item1 = $doc1->importNode($itemi, true);
        // append imported item to document 1 'res' element
        $res1->appendChild($item1);
    }
}
$doc1->save('merged.xml'); //edited -added saving into xml file

【讨论】:

  • 非常感谢!效果很好!我尝试了循环,而没有任何效果。我为自己的错误和对 PHP 的无知感到羞耻。再次感谢!
猜你喜欢
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 2011-08-28
  • 2018-01-31
相关资源
最近更新 更多