2017-04-11 104 views
0

我正在編寫一個API來輸出一個地址簿,其中我得到的輸出爲XML。輸出是JSON。 json_encode創建無用的零密鑰


我的問題是什麼?

我循環遍歷從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); 
} 

這個我想echo在JSON數組後。我用json_encode這樣做。 但有問題。而不是直接給出結果,它表明我下面的結果:

Output of JSON

零的它們是紅色標記的是不應該存在。

我試過

我研究了在互聯網上,並在文檔和在堆棧溢出幾個職位json_encodeJSON_FORCE_OBJECT屬性中找到。 http://php.net/manual/en/function.json-encode.php

現在我的函數如下所示:

echo json_encode($contacts,JSON_FORCE_OBJECT); 

但我仍然得到了零。

這裏也是我的XML的一個小例子:

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

到底哪裏出問題了?

UPDATE:

這裏是的var_dump:

object(SimpleXMLElement)#6 (15) { ["type"]=> string(12) "Organisation" ["name"]=> string(28) "*******" ["occupation"]=> string(57) "*******" ["street"]=> string(11) "Musterstrasse" ["streetno"]=> string(1) "17" ["zip"]=> string(4) "8000" ["city"]=> string(5) "Zürich" ["canton"]=> string(2) "ZH" ["country"]=> string(2) "ch" ["phone"]=> string(12) "+123456789" } 
+0

$ TEL->類型是數組,你可以嘗試像$ tel->類型[0]所有$入口值 –

+0

@Оzgur謝謝,但我也沒有工作。 –

+0

可以在編碼之前將var_dump($ tel)添加到問題中嗎? –

回答

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

非常感謝。它工作得很好。 –