首页  >  文章  >  后端开发  >  如何从 PHP 中的 JSONP 回调中提取 JSON 数据?

如何从 PHP 中的 JSONP 回调中提取 JSON 数据?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-11-01 02:14:28838浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn