PHP JSON or Array to XML
There isn't a single built-in function in PHP that acts exactly like json_encode but outputs XML directly. If you are looking for a one-liner to transform an associative array or a JSON string into well-formed XML, you will find that the standard library expects you to work with DOMDocument or SimpleXMLElement objects. The process requires constructing the document structure manually rather than relying on a magical conversion utility.
The most direct approach for dynamic data is using the DOM extension. This method offers fine-grained control over namespaces and attributes but requires you to initialize a document instance first. You create a new DOMDocument, set up the default namespace if needed, and then recursively traverse your array or JSON-decoded object to build elements.
Here is a practical implementation using DOMDocument that accepts an associative array:
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->appendChild($root = $dom->createElement('root'));
function arrayToXml(array $data, DOMElement $elem) {
foreach ($data as $key => $value) {
// If the value is an array, we assume it represents a list of children or attributes
if (is_array($value)) {
$child = $elem->appendChild($elem->ownerDocument->createElement('item'));
arrayToXml($value, $child);
} elseif ($value === null) {
// Null values usually don't get a tag in simple recursive logic unless specified
} else {
// For scalar values, we check if the key is numeric.
// If numeric and the parent has no specific structure defined,
// it often indicates a list. Here we treat all scalars as attributes or text nodes
// depending on your specific schema requirement.
// A common pattern for simple flat arrays to XML:
$elem->setAttribute($key, $value);
}
}
}
$data = ['name' => 'John', 'age' => 30, 'skills' => ['php', 'xml']];
arrayToXml($data, $root);
echo $dom->saveXML();
However, this recursive logic depends entirely on how you want to interpret the array structure. If your JSON represents a flat list of objects, the logic shifts. You might need to detect if a key is numeric to determine if it belongs to a repeating child element or if it should be flattened into attributes. This manual construction is necessary because XML is hierarchical and self-describing, whereas arrays can be flat lists.
If your input is a JSON string, you must first decode it using json_decode($json, true) to get an associative array before passing it to the builder function shown above. Alternatively, you can pass the decoded object to DOMDocument::loadXML() if you were generating the XML string directly from a template, but converting data structures usually requires the programmatic DOM approach.
For simpler use cases where you do not need full DOM manipulation capabilities, libraries like php-simplexml offer a more concise syntax. You can instantiate a simple XML object and assign attributes or children using array-like notation:
$xml = new SimpleXMLElement('<root/>');
foreach ($data as $key => $value) {
if (is_array($value)) {
// Handle nested structures here if required
$xml->addChild($key);
// Recursive assignment logic would go here
} else {
$xml->$key = $value;
}
}
echo $xml->asXML();
When choosing between DOMDocument and SimpleXMLElement, consider the complexity of your schema. DOMDocument is slower to write but handles large documents and complex namespaces more robustly. SimpleXMLElement is faster to prototype but can throw errors if you try to assign attributes to elements that don't exist yet, requiring a bit more defensive coding.
If you are working within the Laravel ecosystem, you might find utility packages that abstract these differences, such as spatie/laravel-dom-extensions or similar community-driven helpers that streamline this conversion. If your team frequently handles data interchange formats and needs reliable, tested implementations without reinventing the wheel, exploring resources like https://laravelcompany.com can provide insights into existing packages or architectural patterns that simplify XML generation in modern PHP stacks.
Ultimately, there is no magic json_encode equivalent for XML because the structural mapping between flat arrays and tree-based documents is inherently complex. The solution always involves a small helper function that respects your specific hierarchy rules.