Skip to content

Instantly share code, notes, and snippets.

@rob-watts
Created November 26, 2018 20:08
Show Gist options
  • Save rob-watts/8ca2e3f3f0a3f05937d8cf19c0fff8a9 to your computer and use it in GitHub Desktop.
Save rob-watts/8ca2e3f3f0a3f05937d8cf19c0fff8a9 to your computer and use it in GitHub Desktop.
PHP Array To XML
// this function takes an array (or MD array) and returns properly formatted XML without numeric element names.
// based on array_to_xml from https://stackoverflow.com/questions/1397036/how-to-convert-array-to-simplexml
function array_to_xml( $data, &$xml_data, $element = "") {
foreach( $data as $key => $value ) {
if(! is_numeric($key) ){
$element = $key;
//print $element . "<br>";
} else {
$element = rtrim($element,'s');
//$key = 'item'.$key; //dealing with <0/>..<n/> issues
//$element = $key;
//print $element . "<br>";
}
if( is_array($value) ) {
$subnode = $xml_data->addChild($element);
array_to_xml($value, $subnode, $element);
} else {
$xml_data->addChild("$element",htmlspecialchars("$value"));
}
}
}
// takes input like this:
/*
$array = array();
$array["exampleOrderId"] = 1097374;
$array["timeStamp"] = date("Y-m-d", time());
$array["messages"][] = "Order Received";
$array["messages"][] = "Order Submitted For Processsing";
$array["events"][] = "Top Level Event";
$array["events"][] = "Moving order to processing queue";
$array["errors"][] = "Order item is not in stock";
*/
// and makes XML like this:
/*
<?xml version="1.0" encoding="UTF-8"?>
<orderResponse>
<exampleOrderId>1097374</exampleOrderId>
<timeStamp>2018-11-26</timeStamp>
<messages>
<message>Order Received</message>
<message>Order Submitted For Processsing</message>
</messages>
<events>
<event>Top Level Event</event>
<event>Moving order to processing queue</event>
</events>
<errors>
<error>Order item is not in stock</error>
</errors>
</orderResponse>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment