Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
To convert JSON to XML in PHP, decode the JSON with json_decode(), then build the XML explicitly with SimpleXML or XMLWriter. PHP does not provide one universal JSON-to-XML function: you must choose the root element, element names, array representation, and any attributes to match the system that will consume the XML.
Why the XML mapping must be explicit
JSON and XML have different data models. A JSON object has key-value pairs, while XML uses named elements and can also use attributes, namespaces, repeated nodes, and mixed content. JSON does not specify how its values should map to those XML features. Choose a mapping that fits the receiving application or schema before writing the conversion code.
- Choose the root element, such as
recordorperson. - Decide whether a JSON array becomes repeated elements or a container with item elements.
- Choose how to represent nulls, booleans, and numeric values.
- Confirm that keys can be used as valid XML element names; arbitrary JSON keys may not be valid XML names.
- Decide whether any values belong in XML attributes rather than child elements.
Convert a JSON string with SimpleXML
SimpleXML is a convenient choice for building a small XML document in memory. This example decodes an object into an associative array, writes its scalar value as a child element, and writes each skill as a repeated skill element.
<?php
$json = '{"name":"Ada","skills":["PHP","XML"]}';
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
$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')
);
}
echo $xml->asXML();
The result has a record root with one name child and two skill children. The element names and repeated-item convention are choices made for this example, not automatic rules for all JSON. Escape text values for XML before adding them as child content; if values are written into attributes, handle them as attribute values and validate the resulting document against the intended schema.
#1 Best Overall
Choose associative arrays or objects deliberately
The second argument to json_decode() controls whether JSON objects become associative arrays (true) or PHP objects (false, the default). Use the representation that makes your mapping code clearest. PHP arrays can represent both lists and objects depending on their keys, so do not assume every decoded array is a JSON list.
Handle invalid JSON and version differences
With JSON_THROW_ON_ERROR, decoding errors raise JsonException instead of requiring a separate error-code check. Catch that exception where the application can report or recover from malformed input.
Rank #2
<?php
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
// Reject the input or report the decoding error.
}
JSON_THROW_ON_ERROR is available from PHP 7.3.0. The decoder accepts UTF-8 input and has a nesting-depth parameter; PHP documents that an invalid depth raises ValueError as of PHP 8.0.0. Check the PHP runtime version when supporting older installations, and set a depth appropriate to the input rather than assuming deeply nested data will always decode.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Choose SimpleXML or XMLWriter
| Option | How it works | Best fit |
|---|---|---|
| SimpleXML | Builds an in-memory element tree with methods such as addChild() and addAttribute(); asXML() serializes it. |
A small document when convenient tree construction or an XML string is useful. |
| XMLWriter | Writes XML forward-only without caching the output. | Generating a stream or file when you do not want to keep the entire XML output in memory. |
Use PHP SimpleXML when the XML tree is manageable in memory. If you need forward-only output, use PHP XMLWriter, which is designed to generate XML streams or files without caching the output. Either way, your code still has to apply the mapping rules required by the recipient.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Validate the output and handle construction errors
Successful JSON decoding does not guarantee that the XML matches the receiving system’s expectations. Check the generated document for well-formedness and, when available, validate it against the consumer’s schema. Treat XML construction or parsing failures as errors rather than silently sending incomplete output. For XML parsing diagnostics, PHP documents libxml_use_internal_errors(), which lets an application collect libxml errors instead of emitting them directly.
- Reject malformed JSON and handle
JsonExceptionwhen usingJSON_THROW_ON_ERROR. - Verify that keys used as element names are valid, or map them to known-safe names.
- Define behavior for arrays, nulls, booleans, and numeric keys before processing arbitrary input.
- Escape text and attribute values for XML in the context where they are written.
- Check the serialized result against the target schema if one is provided.
For deeper details on decoding behavior and XML error handling, see PHP’s json_decode() documentation and libxml_use_internal_errors() documentation.
Quick Recap
Rank #4
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.
Recommended Free Tools

