5

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;
4

2 回答 2

4

你可以试试

$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

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

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 filterEmptyArray(array &$a) {
    foreach ( $a as $k => &$v ) {
        if (empty($v))
            $a[$k] = "";
        else
            is_array($v) AND filterEmptyArray($v);
    }
}
于 2012-10-18T22:11:09.270 回答
1

我认为上面的函数 filterEmptyArray() 需要添加它以不删除零作为值。例如。0 也会变成 ''

if (empty($v) && is_array($v))
    $a[$k] = "";
}
于 2016-11-16T15:10:26.640 回答