"merge xml files in php" Answer’s

0

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);

    }
Wednesday, March 31, 2021
 
ammezie
answered 11 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :