开发者

Moving a node from one XML document to another using SimpleXML

开发者 https://www.devze.com 2023-01-15 18:37 出处:网络
I realize that my request is not possible using just SimpleXML -- that much I did figure out. Here is what I tried:

I realize that my request is not possible using just SimpleXML -- that much I did figure out. Here is what I tried:

$newXML = simplexml_load_file($filePath); 
$domNewXML = dom_import_simplexml($newXML);
$domItem = dom_import_simplexml($items[$itemQty]);  <-- item I want to move
$domNewItem = $domItem->cloneNode(true);
$newNode = $domNewXML->importNode($domNewItem, true);
$domNewXML->getElementsByTagName('list')->item(0)->appendChild($newNode);

I realize the code errors out on line 5, because importNode is a function of the dom document, not the dom element, but how can I get the开发者_如何学运维 dom document to perform this step?

Am I going about this the right way?

In the grand scheme of things I have an XML file with at least 10 nodes, every day a CRON job checks to see if there are more than 10 nodes and if so, it's supposed to move the node from the current file into an archive file. I figured I would "move" the node by copying it to the archive file and deleting it from the original file.

Thanks for any help!


You can get the owner document via $anyDOMNode->ownerDocument


Maybe it's not necessary to clone and insert the nodes into another document. If you split the archive into a) a skeleton xml document and b) an xml fragment that is included as an external entity into the document it suffices if you just append the xml string representation of the node to the end of the fragment file. E.g. as the skeleton

<?xml version="1.0"?>
<!DOCTYPE fooarchive [
  <!ENTITY entries SYSTEM "archive.fragment">
]>
<fooarchive>
  &entries;
</fooarchive>

and then the php script

$doc = new SimpleXMLElement('<a>
  <b>0</b><b>1</b><b>2</b><b>3</b>
  <b>4</b><b>5</b><b>6</b><b>7</b>
  <b>8</b><b>9</b><b>X</b><b>Y</b>
</a>');

$move = '';
for($i=10; $i<count($doc->b); $i++) {
  $move .= $doc->b[$i]->asXML();
}
file_put_contents('archive.fragment', $move, FILE_APPEND);

for($i=count($doc->b)-1; $i>9; $i--) {
  unset($doc->b[$i]);
}
echo $doc->asXML('current.xml');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号