将XML节点复制到另一个文件

时间:2015-12-18 11:43:51

标签: php xml

我目前正在使用下面的PHP代码来获取' imagepath'然后我遍历XML以删除具有此路径的节点。

<?php       
$id = $_GET['imagepath'];       
$xmldoc = new DOMDocument();
$xmldoc->load('newcoke.xml');
$root   = $xmldoc->documentElement;
$fnode  = $root->firstChild;

$items = $xmldoc->getElementsByTagName('flight');
foreach ($items as $item){
    $node = $item->getElementsByTagName('imagepath')->item(0);
    if ($node->nodeValue == $id){
        $node->parentNode->parentNode->removeChild($node->parentNode);            
    }
}
$xmldoc->save('newXmlFile.xml');
?>

我已经尝试了几个小时,然后以某种方式复制已删除的节点并将其保存到一个新的XML文件中,该文件具有相同的结构,称为“已删除”。有人可以帮忙吗?

这是xml的结构:

<ArrivingFlights>
     <flight>
        <to>Ger</to>
        <from>Mammy xx</from>
        <imagepath>0002.jpg</imagepath>
        <templateStyle>template1</templateStyle>
        <time>08:00</time>
        <date>21/12/15</date>
    </flight>
    <flight>
        <to>Ciara</to>
        <from>Vikki xx</from>
        <imagepath>0003.jpg</imagepath>
        <templateStyle>template1</templateStyle>
        <time>11:00</time>
        <date>17/12/15</date>
    </flight>
</ArrivingFlights>

1 个答案:

答案 0 :(得分:0)

DOMNode::removeChild返回刚删除的节点;这个对象仍然有效...对于DOM信息它已被删除。
要在另一个DOM中使用它,你必须import,然后将它附加到该另一个DOM实例中的某个元素/节点。

if ($node->nodeValue == $id){
    $rn = $node->parentNode->parentNode->removeChild($node->parentNode);
    $deletedFlight = $otherDom->importNode($rn, true); // make a deep-copy for the other DOM
    $otherDom->documentElement->appendChild($deletedFlight);
}

...或者您可以将$ rn传递给DOMDocument::saveXML(),并通过file_put_contents(..,.., FILE_APPEND)将返回值附加到文件中。生成的文件看起来像

<flight>
    <to>Ger</to>
    <from>Mammy xx</from>
    <imagepath>0002.jpg</imagepath>
    <templateStyle>template1</templateStyle>
    <time>08:00</time>
    <date>21/12/15</date>
</flight>
<flight>
    <to>Ciara</to>
    <from>Vikki xx</from>
    <imagepath>0003.jpg</imagepath>
    <templateStyle>template1</templateStyle>
    <time>11:00</time>
    <date>17/12/15</date>
</flight>

这是无效的XML(多个顶级元素)......但...... 您可以将该文件作为实体导入到有效的XML文档中 这样(有点小心)你可以摆脱第二个DOM以及构建它所需的时间和内存。

相关问题