Home > Article > Backend Development > 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:
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] !== '[' && $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&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!