使用PHP删除XLF中的重复条目

时间:2019-01-21 13:03:29

标签: php xml

我有一个XML文件,我想用PHP检查是否有重复的条目,并删除不必要的条目。 我运行了所有的跨单元,将id推入数组并检查条目是否已存在于数组中。 但是,如果我找到一个已经存在的ID,该如何删除反型部队?

我的XLF和我的PHP代码:

    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
        <file source-language="de" target-language="de" datatype="plaintext" original="messages" date="2018-08-24T14:49:31Z" product-name="test">
            <header/>
            <body>
                <trans-unit id="test">
                    <source>123</source>
                    <target/>
                </trans-unit>
                <trans-unit id="test2">
                   <source>123</source>
                   <target/>
                </trans-unit>
                <trans-unit id="test2">
                   <source>123</source>
                   <target/>
                </trans-unit>
                <trans-unit id="test3">
                   <source>123</source>
                   <target/>
                </trans-unit>
                <trans-unit id="test4">
                   <source>123</source>
                   <target/>
                </trans-unit>
            </body>
        </file>
    </xliff>


    function cleanUpXliffFile($file) {
        $transUnitIds = [];
        $xlif = simplexml_load_file($file);
        $xlif->file['source-language'] = "de";
        foreach($xlif->file->body->{'trans-unit'} as $item) {
            $unit = $item->attributes()->id;
            $transUnitId = $unit[0]->__toString();
            if(in_array($transUnitId, $transUnitIds)) {
                //DELETE THE CHILD
            }
            $transUnitIds[] = $transUnitId;
            if (!isset($item->target)) {
                $item->addChild("target");
            }

            if ($item->target->__toString() !== "") {
                $item->source = (string)$item->target;
                $item->target[0] = "";
            }
        }

        $xlif->saveXML($file);
    }

1 个答案:

答案 0 :(得分:1)

使用DOMDocument而不是simplexml的非常简单的小函数似乎可以正常工作。获取对trans-unit节点的引用,如果该ID以前不存在,则将其添加到数组中,并使用removeChild删除重复的节点。这不会对带有target属性的附加欺骗。

function cleanXMLFile( $file ){
    $dom=new DOMDocument;
    $dom->load( $file );

    $tmp=[];
    $col=$dom->getElementsByTagName( 'trans-unit' );

    foreach( $col as $node ){
        if( !array_key_exists( $node->getAttribute('id'), $tmp ) ) $tmp[ $node->getAttribute('id') ]=$node;
        else $node->parentNode->removeChild( $node );
    }

    $dom->save( $file );
}

cleanXMLFile( __DIR__ . '/xlf.xml' );