Follow up: How to set attributes in Root and child in xml using php array?



This is follow up question of this


How to set attributes in root? Like this



<Form xmlns="url" type="TextView" name="Form">


and set an attributes in the child?


In every child, there's different label, name, format, and type.


Like this...



<Field name="Category" label="FormType" value="Test" type="TextView"/>
<Field type="Delimiter"/>
<Field name="ContractNumber" label="Contract number" value="3300000011" format="string"/>


Using this



// creating object of SimpleXMLElement
$xml_Form = new SimpleXMLElement("<?xml version=\"1.0\"?><Form></Form>");
$Form= $xml_Form->createAttribute('xmlns', 'url');
$Form=xml_Form ->addAttribute('label', 'Form');
$Form=xml_Form ->addAttribute('type', 'TextView');
$Form=xml_Form ->addAttribute('name', 'HomeVisitForm');
$Field=$Form->addAttribute('type', 'normal');

array_to_xml($Form,$xml_Form); // function call to convert array to xml
print $xml_Form->asXML(); //saving generated xml file

// function defination to convert array to xml
function array_to_xml($Form, &$xml_Form) {
$child = $xml_Form->addChild("Field");
foreach($Form as $key => $value) {
$child->addAttribute($key, $value);
}
$var = (is_array($value))
? array_to_xml($value, $xml_Form->addChild("$key"))
: $xml_Form->addChild("$key","$value");
}
?>

No comments:

Post a Comment