DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

How to Convert JSON to XML in PHP

Convert JSON to XML in PHP by decoding it with json_decode() and explicitly building the XML structure your receiving system requires.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

<?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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

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 JsonException when decoding with JSON_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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.