Home >Backend Development >PHP Tutorial >How to Extract JSONP Resultset in PHP with jsonp_decode()?

How to Extract JSONP Resultset in PHP with jsonp_decode()?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 11:10:53508browse

How to Extract JSONP Resultset in PHP with jsonp_decode()?

Extracting JSONP Resultset in PHP: Decoding with jsonp_decode()

To access the returned data from a URL like the one you provided, you can utilize PHP's jsonp_decode() function to extract the JSONP resultset. JSONP is a format that embeds JSON data within a JavaScript function call.

Implementation:

  1. Strip the Function Name: Remove the function name (and parentheses) surrounding the JSON data.
  2. Use jsonp_decode() Function: Parse the extracted JSON data using jsonp_decode(). The syntax is:

    <code class="php">$data = jsonp_decode($jsonString, $assoc = false);</code>

Custom jsonp_decode() Function:

The following custom jsonp_decode() function can handle JSONP responses:

<code class="php">function jsonp_decode($jsonp, $assoc = false) { 
    if($jsonp[0] !== '[' &amp;&amp; $jsonp[0] !== '{') { // we have JSONP
       $jsonp = substr($jsonp, strpos($jsonp, '('));
    }
    return json_decode(trim($jsonp,'();'), $assoc);
}</code>

Usage:

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

$yss = fopen($yahooSS,"r");
$data = jsonp_decode($response);

// Accessing the result 
foreach ($data->ResultSet->Result as $result) {
    echo $result->symbol . " - " . $result->name . "\n";
}</code>

DEMO:

This example demonstrates how to retrieve and display the suggested symbols and names from the Yahoo Finance Symbol Suggest API:

<code class="php"><?php

// Get JSONP response
$yahooSS = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=yahoo&callback=YAHOO.Finance.SymbolSuggest.ssCallback";
$result = file_get_contents($yahooSS);

// Decode JSONP
$data = jsonp_decode($result);

// Process results
echo "<table>";
echo "<tr><th>Symbol</th><th>Name</th></tr>";
foreach ($data->ResultSet->Result as $result) {
    echo "<tr><td>" . $result->symbol . "</td><td>" . $result->name . "</td></tr>";
}
echo "</table>";

?></code>

The above is the detailed content of How to Extract JSONP Resultset in PHP with jsonp_decode()?. 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