The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →PHP handles JSON-to-XML conversion in two steps: decode the JSON with json_decode(), then build and serialize an XML document with a library such as SimpleXML or XMLWriter. You must decide the XML structure yourself—the right root element, child names, and array representation depend on the system that will consume the document.
Choose the XML structure before converting
JSON and XML do not prescribe a universal one-to-one mapping. Before writing PHP, determine the target document’s root element, how object properties map to elements or attributes, whether arrays become repeated elements, and how to represent nulls and booleans. If the receiving system provides an XML schema or format specification, follow it and validate the generated document against it.
As an Amazon Associate I earn from qualifying purchases.
JSON object keys are not guaranteed to be valid XML element names. XML also supports namespaces, attributes, and mixed content, while JSON does not define how those features should be inferred. A generic recursive converter therefore needs explicit rules for these cases, as well as for numeric keys and repeated items.
Decode JSON and build a small XML document with SimpleXML
For a modest document that you want to construct in memory and serialize as a string, SimpleXML provides element and attribute methods such as addChild() and addAttribute(), and asXML() serializes the resulting tree.
#1 Best Overall
<?php
$json = '{"name":"Ada","skills":["PHP","XML"]}';
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
throw new RuntimeException('Invalid JSON input', 0, $e);
}
$xml = new SimpleXMLElement('<record/>');
$xml->addChild(
'name',
htmlspecialchars($data['name'], ENT_XML1 | ENT_QUOTES, 'UTF-8')
);
foreach ($data['skills'] as $skill) {
$xml->addChild(
'skill',
htmlspecialchars($skill, ENT_XML1 | ENT_QUOTES, 'UTF-8')
);
}
$output = $xml->asXML();
if ($output === false) {
throw new RuntimeException('Could not serialize XML');
}
echo $output;
This example maps the input to a <record> root, one <name> element, and repeated <skill> elements. Those names and choices are illustrative; change them to match the receiving system. The call to htmlspecialchars() escapes text for XML, including quotes, before it is added as a child value.
Choose the decoded PHP representation deliberately
The second argument to json_decode() determines whether JSON objects become PHP objects or associative arrays. The example uses true so properties can be accessed with array keys. PHP notes that arrays can represent either JSON lists or objects depending on their keys, so do not infer the intended XML structure solely from the resulting PHP type when the input can contain ambiguous keys.
Rank #2
Check the PHP version and input errors
JSON_THROW_ON_ERROR was added in PHP 7.3.0. It makes malformed JSON raise a JsonException, which the example catches. The manual also documents a nesting-depth argument; invalid depth raises ValueError as of PHP 8.0.0. Choose a depth appropriate to the expected input and account for the PHP versions your application supports. See the PHP json_decode() manual for the parameters and error behavior.
Free tools Windows power users keep installed
One-click scans. No signup required.
Use XMLWriter for forward-only output
When you are writing a stream or file and do not need to keep a complete XML tree in memory, XMLWriter provides forward-only, non-cached XML generation. You still need to define the same mapping rules, but you write each element as you process the data instead of building a SimpleXML tree first.
Quick Recap
Rank #4
| Approach | Workflow | Output and memory behavior | Best fit |
|---|---|---|---|
| SimpleXML | Build an in-memory element tree with methods such as addChild() and addAttribute(). |
Keeps a tree in memory; asXML() can return a serialized string. |
Small documents when convenient tree construction or a string result is useful. |
| XMLWriter | Write elements in sequence using a forward-only writer. | Non-cached generation for XML streams or files. | Output that can be written forward to a stream or file without caching the entire XML document. |
Handle conversion failures and validate the result
- Invalid JSON: catch
JsonExceptionwhen decoding withJSON_THROW_ON_ERROR, or check decoding errors using the behavior documented for your PHP version. - Unexpected input shape: verify that required keys exist and that values have the expected types before building elements. A missing property or a nested list may require a different mapping than the example.
- XML construction or serialization problems: treat failure to construct or serialize as an error rather than returning partial output. For XML parsing diagnostics, PHP documents
libxml_use_internal_errors()for collecting errors; consult the PHP manual. - Schema mismatch: check element names, namespaces, required attributes, and repeated-element rules against the consumer’s schema. Well-formed XML is not necessarily valid for that schema.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




