Created
October 8, 2013 01:33
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
?> |
thx ;)
Cheers mate!
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
Hell yeah, 5 years have passed but I still find some nasty integrations that use XML.
Thanks for the snippet, works great