Skip to content

Instantly share code, notes, and snippets.

@david-saint
Last active April 16, 2018 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save david-saint/9c1b36416b98982803a97f78467b272b to your computer and use it in GitHub Desktop.
Save david-saint/9c1b36416b98982803a97f78467b272b to your computer and use it in GitHub Desktop.
Convert any php array or object to XML

Using the XMLSerializer

use App\Helpers\XMLSerializer;

$request = array("conditions" => array(
	"language" => "EN",
	"par_adt" => 1,
	"extraData" => array(
		"_attributes" => array(
			"someRandomAttribute" => "this_is_the_attribute_value"
		),
		"_value" => "This is the value of the extraData"
	),
	"People" => array(
		array("_name" => "person", "name" => "Dave"),
		array("_name" => "person", "_value" => "David")
	),
	"limit_count" => 10
));

return XMLSerializer::generateValidXmlFromArray(self::processRequest($request, $options));

This would output

<conditions>
	<language>EN</language>
	<par_adt>1</par_adt>
	<extraData someRandomAttribute="this_is_the_attribute_value"> This is the value of the extraData </extraData>
	<People>
		<person>
			<name>Dave</name>
		</person>
		<person>David</person>
	</People>
</condition>
<?php
namespace App\Helpers;
class XMLSerializer
{
public static function generateValidXmlFromArray($array, $node_block='nodes', $node_name='node')
{
$xml = self::generateXmlFromArray($array, $node_name);
return $xml;
}
private static function generateXmlFromArray($array, $node_name)
{
$xml = '';
if ((is_array($array) || is_object($array))) {
foreach ($array as $key=>$value) {
if (is_numeric($key)) {
$key = (isset($value['_name'])) ? $value['_name'] : $node_name;
}
if ($key != '_namespace' && $key != '_attributes' && $key != '_value' && $key != '_name') {
$xml .= '<' . $key .self::generateAttributesFromArray($value)
.self::generateNamespace($value)
. '>'
. self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';
}
if ($key == '_value') {
$xml = htmlspecialchars($value, ENT_QUOTES);
}
}
} else {
$xml = htmlspecialchars($array, ENT_QUOTES);
}
return $xml;
}
private static function generateAttributesFromArray($array)
{
if (isset($array['_attributes']) && is_array($array['_attributes'])) {
$attributes = ' ';
foreach ($array['_attributes'] as $key=>$value) {
$attributes .= $key.'="'.$value.'" ';
}
return $attributes;
} else {
return '';
}
}
private static function generateNamespace($namespace)
{
if (isset($namespace['_namespace']) && $namespace['_namespace']) {
return ' xmlns="'.$namespace['_namespace'].'"';
} else {
return '';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment