I am rebuilding a nodes children by saving them out to an array as strings, trashing them in the XML, inserting a new child node into the array as a string... now I want to loop through the array and write them back out to the original node. The problem is I can't find anything on how to add a child node using a string.
See below for my code. Thanks!!!
$xml = simplexml_load_file($url);
$questionGroup = $xml->qa[intval($id)];
$children = array(); // create empty array
foreach ($questionGroup->children() as $element) { // loop thru children
array_push($children, $element->asXML()); // save XML into array
}
//unset($questionGroup->answer);
//unset($questionGroup->question);
//create new node
$newNode = '<answer><title>'.$title.'</title><description>'.$description.'</description><subName>'.$subName.'</subName><date>'.$date.'</date><timestamp>'.$timestamp.'</timestamp></answer>';
echo "children count: ".count($children);
echo "<br /><br />";
print_r($children);
echo "<br /><br />";
// insert new
array_splice($children,intval($elementIndex),0,$newNode);
echo "children count: ".count($children);
echo "<br /><br />";
print_r($children);
echo "<br /><br />";
echo $questionGroup->asXML();
foreach ($children as $element) { // loop thru array
echo "<br /><br />";
echo $element;
//$questionGroup->addChild(simplexml_load_string($element)); // add array element to the empty questionGroup
}
echo "<br /><br />";
echo "questionGroup: ".$questionGroup;
UPDATE: I found a function that I modified and was able to get working:
function append_simplexml(&$simplexml_to, &$simplexml_from)
{
$childNode = $simplexml_to->addChild($simplexml_from->getName(), "");
foreach ($simplexml_from->children() as $simplexml_child)
{
$simplexml_temp = $childNode->addChild($simplexml_child->getName(), (string) $simplexml_child);
foreach ($simplexml_child->attributes() as $attr_key => $attr_value)
{
$simplexml_temp->addAttribute($attr_key, $attr_value);
}
// append_simplexml($simplexml_temp, $simplexml_child);
}
}
With this usage in my foreach() loop:
foreach ($children as $element) { // loop thru array
append_simplexml($questionGroup, new SimpleXMLElement($element));
}