Extracting JSONP Resultset in PHP
JSONP callbacks are a common method of returning data from a JavaScript-based API. In this instance, you have one such endpoint that returns the following JSONP content:
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"}]}})
To extract the JSON data from this content, you can use the jsonp_decode() function:
<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>
With this function, you can access the JSON data as follows:
<code class="php">$data = jsonp_decode($response);</code>
The $data variable will contain an object with the following structure:
{ "ResultSet": { "Query": "yahoo", "Result": [ { "symbol": "YHOO", "name": "Yahoo! Inc.", "exch": "NMS", "type": "S", "exchDisp": "NASDAQ", "typeDisp": "Equity" }, // ... ] } }
You can then access the individual data points as needed.
The above is the detailed content of How do you extract JSON data from a JSONP callback in PHP?. For more information, please follow other related articles on the PHP Chinese website!