tags:

views:

239

answers:

2

I need to load an XML source using Simple XML, duplicate an existing node with all his children, then customize an attribute of this new node before rendering XML. Any suggestion?

A: 

Try the following

// Get the node you need
$node = $xml->root->someNode->nodetoDuplicate[0];

// Edit the node
$node["someAttribute"] = "newValue";

// Add node as a child
$xml->root->someNode[0].addChild($node);
LnDCobra
Please test your code before posting it. None of that would work.
Josh Davis
I confirm that this code doesn't work.
cesko80
+1  A: 

SimpleXML can't do this, so you'll have to use DOM. The good news is that DOM and SimpleXML are two sides of the same coin, libxml. So no matter whether you're using SimpleXML or DOM, you're working on the same tree. Here's an example:

$thing = simplexml_load_string(
    '<thing>
        <node n="1"><child/></node>
    </thing>'
);

$dom_thing = dom_import_simplexml($thing);
$dom_node  = dom_import_simplexml($thing->node);
$dom_new   = $dom_thing->appendChild($dom_node->cloneNode(true));

$new_node  = simplexml_import_dom($dom_new);
$new_node['n'] = 2;

echo $thing->asXML();

If you're doing that kind of thing a lot, you can try SimpleDOM, which is an extension to SimpleXML that lets you use DOM's methods directly, without converting from and to DOM objects.

include 'SimpleDOM.php';
$thing = simpledom_load_string(
    '<thing>
        <node n="1"><child/></node>
    </thing>'
);

$new = $thing->appendChild($thing->node->cloneNode(true));
$new['n'] = 2;

echo $thing->asXML();
Josh Davis