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

How Can I Extract JSONP Resultset in PHP?

Linda Hamilton
Release: 2024-10-30 05:05:28
Original
921 people have browsed it

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

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

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!

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