Skip to content

Instantly share code, notes, and snippets.

@entomb
Created October 8, 2013 01:33
Show Gist options
  • Save entomb/6878021 to your computer and use it in GitHub Desktop.
Save entomb/6878021 to your computer and use it in GitHub Desktop.
Parses an Array to XML, allows for multiple items with the same key, as long as the parent node is a collection. Useful for those nasty SOAP webservices with auto generated and poor WSDL
<?php
$request = array(
'Test' => array(
'innerTest' => array(
'innerInnerTest' => array(
'someVar' => 'ABCabcXYZxyz',
'arrayVar' => array(
'someString' => 'loremipsum',
'someInt' => 123123123,
),
'someItem'=> array(
array('ID'=>1)
),
'listOfItems' => array(
array('someItem'=> array(
array('ID'=>3)
)),
array('someItem'=> array(
array('ID'=>4)
)),
array('someItem'=> array(
array('ID'=>5)
))
)
)
)
)
);
class ArrToXml{
static function parse($arr){
$dom = new DOMDocument('1.0');
self::recursiveParser($dom,$arr,$dom);
return $dom->saveXML();
}
private static function recursiveParser(&$root, $arr, &$dom){
foreach($arr as $key => $item){
if(is_array($item) && !is_numeric($key)){
$node = $dom->createElement($key);
self::recursiveParser($node,$item,$dom);
$root->appendChild($node);
}elseif(is_array($item) && is_numeric($key)){
self::recursiveParser($root,$item,$dom);
}else{
$node = $dom->createElement($key, $item);
$root->appendChild($node);
}
}
}
}
$xmlRequest = ArrToXml::parse($request);
//$params = new SoapVar($xmlRequest, XSD_ANYXML);
header ("Content-Type:text/xml");
echo $xmlRequest;
?>
@tng-sy
Copy link

tng-sy commented Aug 17, 2020

thx ;)

@wizdom75
Copy link

wizdom75 commented Dec 2, 2021

Cheers mate!

@entomb
Copy link
Author

entomb commented Dec 3, 2021

I can't even remember how this code works, happy to see people are still finding a use to it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment