json_encode创建无用的零键

时间:2017-04-11 19:07:18

标签: php json xml

我正在编写一个API来输出地址簿,我将输出作为XML输出。输出是JSON。

<小时/> 我的问题是什么?

我遍历条目,我从XML文件中获取并将其存储在数组中。这意味着,每个条目都包含一个联系人:

$xml = new SimpleXMLElement("adressbook.xml"); // <-- Only an example URL
$totalResults = $xml->children('openSearch', true)->totalResults;

$contacts=array();

foreach($xml->entry as $contact){
  $tel = $contact->children('tel', true);
  $entry = array(
    "type"=>$tel->type,
    "name"=>$tel->name,
    "firstname"=>$tel->firstname,
    "street"=>$tel->street,
    "streetno"=>$tel->streetno,
    "zip"=>$tel->zip,
    "city"=>$tel->city,
    "canton"=>$tel->canton,
    "country"=>$tel->country,
    "phone"=>$tel->phone
  );
  array_push($contacts,$entry);
}

在此之后我想在json中echo数组。我用json_encode执行此操作。 但是有问题。它不是直接给出结果,而是显示以下结果:

Output of JSON

红色标记的零不应该存在。

我尝试了什么

我在互联网上进行了研究,并在文档和Stack Overflow上的一些帖子中找到JSON_FORCE_OBJECT的{​​{1}}属性。 http://php.net/manual/en/function.json-encode.php

现在我的功能看起来像这样:

json_encode

但我仍然得到了零。

这也是我的XML的一个小例子:

echo json_encode($contacts,JSON_FORCE_OBJECT);

出了什么问题?

更新

这是var_dump:

<entry>
    <updated>2017-04-11T02:00:00Z</updated>
    <published>2017-04-11T02:00:00Z</published>
    <title type="text">Mustermann, Max</title>
    <tel:type>Person</tel:type>
    <tel:name>Mustermann</tel:name>
    <tel:firstname>Max</tel:firstname>
    <tel:street>Musterstrasse</tel:street>
    <tel:streetno>17</tel:streetno>
    <tel:zip>8000</tel:zip>
    <tel:city>Zürich</tel:city>
    <tel:canton>ZH</tel:canton>
    <tel:country>ch</tel:country>
    <tel:phone>+123456789</tel:phone>
</entry>

1 个答案:

答案 0 :(得分:1)

一种方法是使用strval将每个对象转换为字符串

$xml = new SimpleXMLElement("adressbook.xml"); // <-- Only an example URL
$totalResults = $xml->children('openSearch', true)->totalResults;

$contacts=array();

foreach($xml->entry as $contact){
  $tel = $contact->children('tel', true);
  $entry = array(
    "type"=>strval($tel->type),
    "name"=>strval($tel->name),
    "firstname"=>strval($tel->firstname,)
    "street"=>strval($tel->street),
    "streetno"=>strval($tel->streetno),
    "zip"=>strval($tel->zip),
    "city"=>strval($tel->city),
    "canton"=>strval($tel->canton),
    "country"=>strval($tel->country),
    "phone"=>strval($tel->phone)
  );
  array_push($contacts,$entry);
}