Search code examples
phpxmldomdocumentphp-7.1clonenode

PHP 7.1 XML domDocument clone node with subnodes


I have to solve this problem with PHP and DomDocument (also simplexml could be OK). I've googled alot but not found a right example to learn how to do:

I have the following eBay XML

<?xml version="1.0" encoding="utf-8"?>
<ReviseInventoryStatusRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <RequesterCredentials>
    <eBayAuthToken>INSERT_TOKEN</eBayAuthToken>
  </RequesterCredentials>
  <InventoryStatus>
    <ItemID> ItemIDType (string) </ItemID>
    <Quantity> int </Quantity>
    <SKU> SKUType (string) </SKU>
    <StartPrice> AmountType (double) </StartPrice>
  </InventoryStatus>
  <ErrorLanguage>en-US</ErrorLanguage>
  <Version> string </Version>
  <WarningLevel>Low</WarningLevel>
</ReviseInventoryStatusRequest>

and I need to clone (actually 4 times) the <InventoryStatus> Node with all its subnodes:

  <InventoryStatus>
    <ItemID> ItemIDType (string) </ItemID>
    <Quantity> int </Quantity>
    <SKU> SKUType (string) </SKU>
    <StartPrice> AmountType (double) </StartPrice>
  </InventoryStatus>

and append just under the current Node

Can pls give some hints

Thanks!


Solution

  • DOMDocument is much better at handling things like this and can just clone nodes with cloneNode(), passing true does a deep clone which will copy the content as well. You can then add the node back in where you need it...

    $dom = new DOMDocument();
    $dom->load("data.xml");
    
    $is = $dom->getElementsByTagName("InventoryStatus");
    $dom->documentElement->appendChild($is[0]->cloneNode(true));
    $dom->documentElement->appendChild($is[0]->cloneNode(true));
    $dom->documentElement->appendChild($is[0]->cloneNode(true));
    $dom->documentElement->appendChild($is[0]->cloneNode(true));
    echo $dom->saveXML();