I restore the children nodes by storing them in the array as strings, spoofing them in XML, inserting the new node child into the array as a string ... now I want to loop through the array and write them back to the original node. The problem is that I can not find anything about how to add a child of a node using a string.
See my code below. Thanks!!!
$xml = simplexml_load_file($url);
$questionGroup = $xml->qa[intval($id)];
$children = array();
foreach ($questionGroup->children() as $element) {
array_push($children, $element->asXML());
}
$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 />";
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) {
echo "<br /><br />";
echo $element;
}
echo "<br /><br />";
echo "questionGroup: ".$questionGroup;
UPDATE: I found a function that I modified and was able to work:
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);
}
}
}
With this use in my foreach () loop:
foreach ($children as $element) {
append_simplexml($questionGroup, new SimpleXMLElement($element));
}
source
share