问题描述:

I am currently using the below PHP code to get an 'imagepath', then I loop through the XML to delete the node that has this path.

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

?>

I have been trying it for hours to then somehow copy the deleted node and save it into a new XML file with the same structure that exists called 'deleted'. Can anybody help?

This is the structure of the 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>

网友答案:

DOMNode::removeChild returns the node it just has removed; this object is still valid ...for the DOM istance it has been removed from.
To use it in another DOM you have to import it, before appending it to some element/node in that other DOM instance.

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

...or you can pass $rn to DOMDocument::saveXML() and append the return value to a file via file_put_contents(..,.., FILE_APPEND). The resulting file would look like

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

which is not valid XML (more than one top-level element) ...but ... You can import that file as an entity into a valid XML document.
That way (being a little careful) you could get rid of the second DOM and the time and memory it takes to build it.

相关阅读:
Top