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

Mary-Kate Olsen
发布: 2024-11-01 02:14:28
原创
838 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!