Extracting JSONP Resultset in PHP
This query delves into the process of accessing data returned from a URL that uses JSONP (JSON with Padding), as exemplified by the provided Yahoo Finance URL. PHP possesses the capabilities to retrieve this data.
The response received from the URL is enwrapped by a JavaScript callback function, which complicates direct JSON parsing. To access the actual JSON result set, we need to remove the function name and parentheses from the response.
Fortunately, a PHP function can assist in this extraction:
<code class="php">function jsonp_decode($jsonp, $assoc = false) { if($jsonp[0] !== '[' && $jsonp[0] !== '{') { $jsonp = substr($jsonp, strpos($jsonp, '(')); } return json_decode(trim($jsonp,'();'), $assoc); }</code>
This function effectively uncovers the underlying JSON data, enabling us to parse it using PHP's built-in json_decode function.
<code class="php">$data = jsonp_decode($response);</code>
This method grants us access to the JSON result set, stored in the $data variable, which can then be further processed as needed.
The above is the detailed content of How Can I Extract JSONP Resultset in PHP?. For more information, please follow other related articles on the PHP Chinese website!