在 PHP 中提取 JSONP 結果集
JSONP 回呼是從基於 JavaScript 的 API 傳回資料的常見方法。在這種情況下,您有一個這樣的端點,它會傳回以下JSONP 內容:
YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"yahoo","Result":[{"symbol":"YHOO","name": "Yahoo! Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"YAHOY.PK","name": "YAHOO JAPAN CORP","exch": "PNK","type": "S","exchDisp":"Pink Sheets","typeDisp":"Equity"},{"symbol":"ETD","name": "Citigroup Inc. ELKS On Yahoo","exch": "PCX","type": "S","typeDisp":"Equity"},{"symbol":"YOJ.BE","name": "YAHOO JAPAN","exch": "BER","type": "S","exchDisp":"Berlin","typeDisp":"Equity"},{"symbol":"YHO.SG","name": "YAHOO","exch": "STU","type": "S","exchDisp":"Stuttgart","typeDisp":"Equity"},{"symbol":"YAHOF.PK","name": "YAHOO JAPAN CORP","exch": "PNK","type": "S","exchDisp":"Pink Sheets","typeDisp":"Equity"},{"symbol":"YHO.HM","name": "YAHOO","exch": "HAM","type": "S","exchDisp":"Hamburg","typeDisp":"Equity"},{"symbol":"YOJ.DE","name": "YAHOO JAPAN","exch": "GER","type": "S","exchDisp":"XETRA","typeDisp":"Equity"},{"symbol":"YHO.DU","name": "YAHOO","exch": "DUS","type": "S","exchDisp":"Dusseldorf Stock Exchange","typeDisp":"Equity"},{"symbol":"YHOO.BA","name": "YAHOO INC.","exch": "BUE","type": "S","exchDisp":"Buenos Aires","typeDisp":"Equity"}]}})
要從此內容中提取JSON 數據,您可以使用jsonp_decode() 函數:
<code class="php">function jsonp_decode($jsonp, $assoc = false) { // PHP 5.3 adds depth as third parameter to json_decode if($jsonp[0] !== '[' && $jsonp[0] !== '{') { // we have JSONP $jsonp = substr($jsonp, strpos($jsonp, '(')); } return json_decode(trim($jsonp,'();'), $assoc); }</code>
使用此函數,您可以如下存取JSON 資料:
<code class="php">$data = jsonp_decode($response);</code>
$data 變數將包含具有以下結構的物件:
{ "ResultSet": { "Query": "yahoo", "Result": [ { "symbol": "YHOO", "name": "Yahoo! Inc.", "exch": "NMS", "type": "S", "exchDisp": "NASDAQ", "typeDisp": "Equity" }, // ... ] } }
然後您可以存取根據需要的各個數據點。
以上是如何從 PHP 中的 JSONP 回呼中提取 JSON 資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!