Merge XML files in PHP

后端 未结 3 1847
半阙折子戏
半阙折子戏 2020-12-01 12:40

I have 2 files 1.xml and 2.xml both having similar structure and I would like to have one. I tried many solutions but I had errors only - frankly s

3条回答
  •  半阙折子戏
    2020-12-01 12:57

    Since you've put an effort in, I've coded something that should work.

    Note that this is untested code, but you get the idea.

    It's up to you to make it into pretty functions. Make sure you understand what's going on; being able to work with the DOM will probably help you out in a lot of future scenarios. The cool thing about the DOM standard is that you have pretty much the same operations in many different programming languages/platforms.

        $doc1 = new DOMDocument();
        $doc1->load('1.xml');
    
        $doc2 = new DOMDocument();
        $doc2->load('2.xml');
    
        // get 'res' element of document 1
        $res1 = $doc1->getElementsByTagName('res')->item(0);
    
        // 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);
    
        }
    

提交回复
热议问题