2011-01-26 62 views
1

可能有人請幫助我對這個我有以下的JSON字符串問題用PHP和JSON

string(1223) "YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"google","Result":[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}]}})" 

但我似乎無法得到它的任何地方。基本上我只想環出了這是

[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}] 

對不起,結果我的問題是我怎麼能循環,甚至打印的第一個結果例如

{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"} 
+0

哎呀我誤解的問題錯在一開始也是因爲你格式化一點點的你需要指定如何查詢(API)該數據(JSON-P)。你不應該提供回調。 – Alfred 2011-01-26 12:14:05

回答

3

您的字符串不是JSON,它是JSON-的腳本。注意,表示該片段:

YAHOO.Finance.SymbolSuggest.ssCallback(...)

當瀏覽器接收到上述腳本(實際上是一個JavaScript代碼),它會調用YAHOO.Finance.SymbolSuggest.ssCallback函數,傳遞JSON數據作爲參數。

您沒有提及您是否想訪問服務器端或客戶端上的JASON數據?它是它的服務器端(PHP),那麼你可以使用正則表達式或字符串替換函數來提取你喜歡的部分。您可以使用json_decode()函數將結果字符串轉換爲關聯數組。

編輯----

一個快速和骯髒的黑客對JSONP轉換成JSON:

<?php 
    $text = 'YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"google","Result":[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}]}})'; 
    # //CONVERT JSONP to JSON\\ 
    $text = preg_replace('/.+?({.+}).+/', '$1', $text); 
    # \\CONVERT JSONP to JSON// 
    $data = json_decode($text); 
    var_dump($data); 
    var_dump($data->ResultSet->Result[0]); 
    var_dump($data->ResultSet->Result[0]->symbol); 
    var_dump($data->ResultSet->Result[0]->name); 
    # etc etc 
?> 
+0

這將是最好的方式來做它的客戶端或服務器端? – 2011-01-26 12:22:14

1

你的結果不只是一個JSON字符串,它是一個JSON字符串,前面是對JSON函數的調用。這當然是一個JSONP電話。 您必須編寫YAHOO.Finance.SymbolSuggest.ssCallback(data) JavaScript函數並獲取Json。檢查JSONP查詢,如果需要另一個名稱,則應該能夠更改此反向引用函數的名稱,通常使用GET查詢中的參數。

現在你也許直接從PHP調用它,你不在js envirronment。所以你必須寫在你的PHP代碼刪除YAHOO.Finance.SymbolSuggest.ssCallback(部分東西和)解析它作爲JSON數據之前..