首頁 > 後端開發 > php教程 > 如何從 PHP 中的 JSONP 回呼中提取 JSON 資料?

如何從 PHP 中的 JSONP 回呼中提取 JSON 資料?

Mary-Kate Olsen
發布: 2024-11-01 02:14:28
原創
904 人瀏覽過

How do you extract JSON data from a JSONP callback in PHP?

在 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] !== '[' &amp;&amp; $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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板