Home >Backend Development >PHP Tutorial >How to Extract JSONP Resultset in PHP?

How to Extract JSONP Resultset in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 18:25:30913browse

How to Extract JSONP Resultset in PHP?

Extracting JSONP Resultset in PHP

Introduction

The given task involves retrieving and parsing data from a URL that returns a JSONP (JSON with padding) response. PHP offers capabilities to handle such responses effectively.

PHP Implementation

The JSONP response consists of JavaScript code wrapped around a JSON payload. To extract the actual JSON, remove the callback function name and parentheses from the beginning of the response. Subsequently, the PHP function json_decode() can be utilized to parse the JSON into an associative array or an object.

Custom Function for JSONP Decoding

For convenience, a custom function named jsonp_decode() can be defined:

<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>

Usage

Employing this custom function, the JSONP data can be extracted as follows:

<code class="php">$data = jsonp_decode($response);</code>

Example

Consider the example JSONP response provided:

YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"yahoo","Result":[{"symbol":"YHOO","name": "Yahoo! Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"}...]}})

Using the jsonp_decode() function:

<code class="php">$data = jsonp_decode($response);
$query = $data['ResultSet']['Query'];
foreach ($data['ResultSet']['Result'] as $result) {
    echo "Symbol: ".$result['symbol']." - Name: ".$result['name']." - Exchange: ".$result['exch']."\n";
}</code>

This code will extract the query string, along with the symbols, names, and exchange information from the JSONP response.

The above is the detailed content of How to Extract JSONP Resultset in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn