Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract JSONP Resultset in PHP

Tags:

php

jsonp

I would like to be able to get to the returned data of this url. Can I even do this in PHP?

    <?php
    $yahooSS = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=yahoo&callback=YAHOO.Finance.SymbolSuggest.ssCallback";

    $yss = fopen($yahooSS,"r");
    ....

I believe this returns a Javascript callback function, but I don't have a clue where to start.

Below is an example of the returned Resultset.

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"}]}})

Any help is greatly appreciated.

like image 652
Steve Avatar asked Feb 22 '11 17:02

Steve


1 Answers

Right, it is JSON with padding. You have to remove the function name (and parenthesis) and then you can parse the JSON with json_decode.

I once wrote a function for that:

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);
}

Usage:

$data = jsonp_decode($response);

DEMO

like image 92
Felix Kling Avatar answered Oct 16 '22 03:10

Felix Kling