2011-04-26 132 views
3

這是一個小問題。我正在與一個JSON文件,看起來像這樣:用PHP解析JSON數據

{"nodes": 
    [{"node": 
    {"Vocabulary name":"Bestseller Format", 
     "Term":"Hardcover Fiction", 
     "Bestseller1":"9780470227800", 
     "Bestseller2":"9781451617962", 
     "Bestseller3":"9781439167397", 
     "Bestseller4":"9781617750106", 
     "Bestseller5":"9780385533300", 
     "Bestseller6":"9780670022526", 
     "Bestseller7":"9781609530358", 
     "Bestseller8":"9780132358040", 
     "Bestseller9":"9780596159771", 
     "Bestseller10":"9780151014163", 
     "Bestseller11":"9780393334807", 
     "Bestseller12":"9780805090161"} 
    }] 
} 

而我想解析它在PHP中。我想出了一個腳本

<?php  
    $jsonurl = "http://www.xtracrunchy.com/pandpnewlook/?q=pandp/bestsellers"; 
    $json = file_get_contents($jsonurl,NULL, NULL, 0, 1000); 
    $json_output = json_decode($json,true); 

    $bestseller_array = $json_output[nodes][0][node]; 

    foreach ($bestseller_array as $key => $value) 
    { 
    print $key; 
    print " - "; 
    print $value; 
    print "<br />"; 
    } 

?> 

我希望能夠當我運行此腳本是

詞彙名,最終打造暢銷書ISBN的有序列表,但唯一的輸出我得到的 - 暢銷書格式 術語 - 精裝小說

當我添加打印計數($ bestseller_array);我只在數組中獲得2個元素。

任何幫助,將不勝感激。

+0

你可以把代碼放在代碼標籤中嗎?並使一切可讀...謝謝:D – fingerman 2011-04-26 22:56:51

+0

修正了我自己的格式。下一次,在每行代碼前添加4個空格。 – Christian 2011-04-26 22:59:42

+0

謝謝@christian – fingerman 2011-04-26 23:00:41

回答

1

首先,我強烈建議你使用捲曲的,而不是file_get_contents()的,因爲在some occasions,它不會工作。但既然這不是問題的一部分,我不會再談這個問題。

其次,你正在使用未命名的文字常量,這是非常糟糕的。

$json_output[nodes][0][node]; 

應該是:

$json_output['nodes'][0]['node']; 

documentation here on why

最後,您在上面寫的JSON字符串與該網址上返回的內容不匹配,並且該腳本按照預期在此「新」json上工作。

+0

謝謝。這實際上很有幫助。它仍然不起作用,但是這種指向我的方向是正確的。 – flakes 2011-04-26 23:19:58

1

@flakes,如果你訪問在$ jsonurl你的網址,你只能得到:

{"nodes":[{"node":{"Vocabulary name":"Bestseller Format","Term":"Hardcover Fiction"}}]} 

你確定你不會錯過從URL的東西嗎?

0

服務器的輸出與您的期望不符。

var_dump($json); 
//string(87) "{"nodes":[{"node":{"Vocabulary name":"Bestseller Format","Term":"Hardcover Fiction"}}]}" 

希望幫助...的