I have created a simple method used to accept an array of $key=>$value pairs. I want to loop through that array and build a simpleXML object. The method almost works; however, it overwrites my child nodes through each iteration.
The code:
public function format_comment($fieldValues)
{
$xml = new SimpleXMLElement("<ROOT></ROOT>");
foreach($fieldValues as $field=>$value)
{
if($field=='header')
{
$xmlChange = $xml->addChild('CHANGE');
$xmlChange->addAttribute('field', $value);
}
elseif($field=='subheader')
{
$newXML = $xmlChange->addChild('NEW');
$newXML->addAttribute('field', $value);
}
elseif($field=='newvalue')
{
$xmlNewValue = $newXML->addChild('VALUE', $value);
}
elseif($field=='oldvalue')
{
$xmlFrom = $xmlChange->addChild('FROM');
$xmlFrom->addAttribute('field', $field);
$xmlFromValue = $xmlFrom->addChild('VALUE', $value);
}
}
return($xml->asXML());
}
As input, I am using the following array:
$note_fields = array('header'=>'Communication', 'subheader'=>'contacted', 'newvalue'=>'Dale J Neimeier','header'=>'Communication', 'subheader'=>'note', 'newvalue'=>'blah blah blah', 'header'=>'Communication', 'subheader'=>'note', 'newvalue'=>'new text', 'oldvalue'=>'previous text');
My output is as follows:
<ROOT>
<CHANGE field="Communication">
<NEW field="note">
<VALUE>new text</VALUE>
</NEW>
<FROM field="oldvalue">
<VALUE>previous text</VALUE>
</FROM>
</CHANGE>
</ROOT>
I can see that every iteration through my array, the “CHANGE’ tag and all it’s children get overwritten. I just can’t figure out why and how to fix it.
Any help would be most appreciated.
The problem was actually in the way I constructed the $note_fields array. Since I have repeating keys, they just overwrote each other.