Home  >  Article  >  Backend Development  >  How Can I Extract JSONP Resultset in PHP?

How Can I Extract JSONP Resultset in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 05:05:28829browse

How Can I Extract JSONP Resultset in PHP?

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] !== '[' &amp;&amp; $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!

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