我想要得到一個書籍列表,我從XML解析並希望輸出爲JSON。使用SimpleXML從XML構建JSON時出現的問題
我想JSON格式爲:
[
"1" : {
"Title": "Sidemen: The Book",
"ISBN": "1473648165",
"Rating": "4.5"
},
...
]
然而,結果出來是這樣的:
[
{
"title":{
"0":"Sidemen: The Book"
},
"ISBN":{
"0":"1473648165"
}
},
{
"title":{
"0":"DanTDM: Trayaurus and the Enchanted Crystal"
},
"ISBN":{
"0":"1409168395"
}
},
{
"title":{
"0":"Pok\u00e9mon Sun & Pok\u00e9mon Moon: The Official Strategy Guide"
},
"ISBN":{
"0":"1911015109"
}
},
{
"title":{
"0":"Guinness World Records 2017 Gamer's Edition"
},
"ISBN":{
"0":"1910561398"
}
},
{
"title":{
"0":"Minecraft: Blockopedia: An Official Minecraft Book from Mojang"
},
"ISBN":{
"0":"1405273534"
}
},
{
"title":{
"0":"Final Fantasy XV - The Complete Official Guide - Collector's Edition"
},
"ISBN":{
"0":"1911015001"
}
},
{
"title":{
"0":"Harry Potter: Collectible Quidditch Set"
},
"ISBN":{
"0":"076245945X"
}
},
{
"title":{
"0":"Pok\u00e9mon Go The Unofficial Field Guide: Tips, tricks and hacks that will help you catch them all!"
},
"ISBN":{
"0":"1783707712"
}
},
{
"title":{
"0":"Minecraft 2017 Annual (by GamesMaster) (2017 Annuals)"
},
"ISBN":{
"0":"0995495025"
}
},
{
"title":{
"0":"World of Warcraft The Official Cookbook"
},
"ISBN":{
"0":"1785654349"
}
}
]
我似乎無法弄清楚這是爲什麼不做我想做的事(因爲我是一個noob)。這是用PHP生成的,如下所示:
$bookList = array();
$id = 0;
foreach ($parsed_xml->Items->Item as $item) {
$response = file_get_contents($GoodReadsProductLink);
$parsed_xml = simplexml_load_string($response);
$currentBook = array(
"title" => $item->ItemAttributes->Title,
"ISBN" => $item->ItemAttributes->ISBN,
"Rating" => $item->ItemAttributes->Rating
);
$bookList[$id] = $currentBook;
$id++;
}
$jsonOutput = json_encode($bookList);
var_dump($jsonOutput);
任何人都可以看到問題,並幫助我正確地格式化JSON輸出?
的你想要的格式不是有效的JSON ......你能告訴我們什麼地方錯了目前你得到了什麼? –
另外,您可能想要將這些simplexml元素轉換爲字符串。例如。 '「title」=>(string)$ item-> ItemAttributes-> Title'。另外,它看起來不像「評級」實際存在? –
@ john-stirling是不是有效的JSON?是我正在做的正確方法的輸出?我希望每本書的編號都是 – JamesG