How to Extract JSONP Resultset in PHP?

Mary-Kate Olsen
Release: 2024-10-30 18:25:30
Original
852 people have browsed it

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>
Copy after login

Usage

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

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

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"}...]}})
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!