Json_encode creates empty objects for empty XML tags

I have an XML file in which some tags can sometimes 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 the same as they are, empty lines. What is the best way to stop / avoid this conversion?

EDIT: I prefer not to remove these tags from XML, because for me there is a difference between writing an XML without a specific tag and writing an XML so that this tag is empty.

EDIT 2: sample input:

<Family> <name>aaa</name> <adults>3</adults> <kids /> </Family> 
Tag

kids is empty

I would like to get coding results as

 Family[1].name = 'aaa'; Family[1].adults = 3; Family[1].kids = ''; 

I get:

 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; 
+4
source share
2 answers

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 

Front

 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); } } 
+3
source

I think that the filterEmptyArray () function above needs to be complemented with it so as not to remove zeros as values. For instance. 0 will also become "

 if (empty($v) && is_array($v)) $a[$k] = ""; } 
0
source

Source: https://habr.com/ru/post/1440659/


All Articles