PHP > json_encode , force the creation of an array even if it has only one element

If this is the structure of the entire XML and not just a fragment from something bigger, you can turn it into an array or a mix of arrays and objects using less code:

$xml = simplexml_load_string($getPostData);

$array = array('item' => array());
foreach ($xml->item as $item) {
    $array['item'][] = (object)(array)$item;
}

echo(json_encode($array));

This will produce the output you described in the question as expected, no matter how many <item> elements appear in the XML.

Remove the (object) from the code inside the foreach() to get the <item> elements converted to arrays instead of stdClass objects.

Tags:

Php

Json