PHP convert XML to JSON

PHP convert XML to JSON

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP Convert XML to JSON: Handling Attributes and Indexing

When converting XML to JSON in PHP using SimpleXMLElement and json_encode, a common stumbling block involves how the library handles attributes versus child elements. If you load an XML file directly into a SimpleXML object and pass it straight to json_encode, you will notice that attributes defined on the root node or child nodes are completely ignored by default. The output contains only the text content of child elements, leaving tags like id or custom properties invisible in the resulting JSON.

To resolve this, you must explicitly tell SimpleXML to include attributes during serialization. The standard approach is to cast the object to an array before encoding. By setting the LIBXML_NOATTR flag to false (which is actually the default) or more commonly by accessing the underlying DOM structure, you can ensure data integrity. However, a simpler pattern often involves using the asArray() method available in PHP 5.4 and later, or casting the object directly with (array).

Consider this scenario where you have a file named states.xml containing state abbreviations and names:

<?xml version="1.0" ?>
<states>
    <state id="AL">     
        <name>Alabama</name>
    </state>
    <state id="AK">
        <name>Alaska</name>
    </state>
</states>

If you iterate over the children and build an array manually like this:

$xml = simplexml_load_file("states.xml");
$states = [];

foreach ($xml->children() as $state) {
    // This approach misses the 'id' attribute entirely because 
    // SimpleXML separates attributes from child elements in the object structure.
    $states[] = ['state' => $state->name];
}
echo json_encode($states);

The resulting JSON looks like this: [{"state":{"0":"Alabama"}},{"state":{"0":"Alaska"}}].

There are two distinct issues here. First, the id attribute is missing because simplexml_load_file loads attributes into a separate namespace (@attributes) unless accessed explicitly. Second, and more critically, you are seeing an array index key ("0") in your output. This happens because SimpleXML treats child elements within a single parent node as an indexed list when iterating via certain methods or when the structure implies multiple children of the same name.

In the provided code example, $state->name is accessed correctly as text content, but if you are seeing {"0":"Alabama"}, it implies that the iteration logic is returning the child element itself rather than just its value, or the variable assignment inside the loop is inadvertently creating a nested structure. Specifically, if you assign the SimpleXMLElement object directly to the array key without extracting the scalar value, json_encode might treat the object properties as an associative array with numeric keys if not handled carefully.

To fix the attribute loss and ensure clean scalar values, use the following pattern:

$xml = simplexml_load_file("states.xml");
$states = [];

foreach ($xml->state as $state) {
    // Extract text content using (string)$state or $state->name
    // Ensure attributes are included by casting to array or using specific methods
    $attributes = (array) $state; 
    
    // Merge attributes into the data structure explicitly
    $data = [
        'id' => isset($attributes['@attributes']['id']) ? $attributes['@attributes']['id'] : null,
        'name' => (string)$state->name
    ];
    
    $states[] = ['state' => $data];
}

echo json_encode($states);

Alternatively, if you are using a newer version of PHP or Laravel where XML handling is less manual, you can leverage the SimpleXMLElement::asArray() method to convert the entire object into an associative array first. This method respects attributes and converts child elements into arrays with numeric keys, which json_encode handles predictably.

One significant trade-off in these conversions is the difference between indexed and associative keys in XML versus JSON. XML relies heavily on element order and nesting, while JSON prefers flat structures or explicitly named keys. When converting, you must decide whether to flatten the data into a single array of objects or maintain the nested structure of the original DOM.

If your goal is to build a clean API response where each state is an object with id and name properties rather than a nested array, ensure you are extracting scalar values using (string) casting. This prevents json_encode from interpreting SimpleXML objects as associative arrays based on their internal property keys.

For developers working within the Laravel ecosystem, similar patterns exist but are often abstracted away via packages like spatie/laravel-xml or built-in services that handle DOMDocument conversion more flexibly. While manual parsing with SimpleXML works for straightforward documents, complex schemas with namespaces require careful handling of the @attributes collection to avoid data loss during serialization.

Our network