且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 PHP 中合并 XML 文件

更新时间:2023-11-07 14:22:10

既然你付出了努力,我已经编写了一些应该有用的东西.

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

请注意,这是未经测试的代码,但您懂的.

把它变成漂亮的函数取决于你.确保您了解正在发生的事情;能够使用 DOM 可能会在很多未来的场景中帮助你.DOM 标准很酷的一点是,您可以在许多不同的编程语言/平台中使用几乎相同的操作.

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

    }