json_encode creates empty objects for empty XML tags
json, php, xml
Solution
You can try
$xml = '<Family>
<name>aaa</name>
<adults>3</adults>
<kids />
<sub>
<tag>Nice </tag>
<tag>Food </tag>
<tag />
</sub>
</Family>';
$xml = new SimpleXMLElement($xml);
$json = json_encode($xml, JSON_NUMERIC_CHECK);
$json = json_decode($json, true);
var_dump($json); // Before
filterEmptyArray($json); // <------ Filter Empty Array
var_dump($json); // After
Before
array
'name' => string 'aaa' (length=3)
'adults' => int 3
'kids' =>
array <------------------- Empty Array
empty
'sub' =>
array
'tag' =>
array
0 => string 'Nice ' (length=5)
1 => string 'Food ' (length=5)
2 =>
array
...
After
array
'name' => string 'aaa' (length=3)
'adults' => int 3
'kids' => string '' (length=0) <---------- String Conversion
'sub' =>
array
'tag' =>
array
0 => string 'Nice ' (length=5)
1 => string 'Food ' (length=5)
2 => string '' (length=0) <---------- Supports Recursion (2nd level)
Function Used
function filterEmptyArray(array &$a) {
foreach ( $a as $k => &$v ) {
if (empty($v))
$a[$k] = "";
else
is_array($v) AND filterEmptyArray($v);
}
}
Problem
I have an XML file where some tags occasionally may be empty. When I read this file using PHP and encode it using json_encode, JSON converts all my empty tags to empty objects, while I prefer them exactly as they are - empty strings. What is the best way to stop /avoid this conversion? EDIT: I prefer not to delete these tags from XML as for me there is a difference between an XML entry without specific tag and an XML entry with this tag being empty. EDIT 2: sample input: ``` <Family> <name>aaa</name> <adults>3</adults> <kids /> </Family> ``` kids tag is empty I would like to get encoding results as ``` Family[1].name = 'aaa'; Family[1].adults = 3; Family[1].kids = ''; ``` What I am getting is: ``` Family[1].name = 'aaa'; Family[1].adults = 3; Family[1].kids = Object(); //empty ``` EDIT3: My implementation is very simple: in PHP ``` $xml = simplexml_load_file($filepath); echo json_encode($xml, JSON_NUMERIC_CHECK); ``` in JavaScript ``` objJson = $.parseJSON(xmlhttp.responseText); .... d["name"] = objJson.Family[i].name; d["adults"] = objJson.Family[i].adults; d["kids"] = objJson.Family[i].kids; ```