I am having a problem parsing 'jsonp' request with php's json_decode
function.
My questions is
a. What is the use of call back function in 'jsonp', should i just trip that off, or am I suppose to use it in some manner. ?
b. How can I rectify the syntax error received in 'jsonp' format ?
Below I have given the code and the response that I get.
1. I request a sample url with PHP's curl
$url = 'https://ssl.domain.com/data/4564/d.jsonp';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
$feed = curl_exec($ch);
curl_close($ch);
echo $feed = gzdecode($feed); // Success its displays the jsonp feed
2. Then I try to json_decode the received output, which throws the error no 4 meaning JSON_SYNTAX_ERROR, the reason I guess is because names of string type in jsonp are not quoted. e.g. Categories
, Name
, Position
etc.
$json_feed = json_decode($feed);
$error = json_last_error();
echo $error; // Throws error no. 4
3. RAW 'jsonp' output from the url.
domain_jsonp_callback({
Categories:[
{
Name:"Artifacts",
Position:14,
Count:70,
ImageUrls:{
i100:"//s3-eu-west-1.amazonaws.com/s.domain.com/1.png",
i120:"//s3-eu-west-1.amazonaws.com/s.domain.com/2.png",
i140:"//s3-eu-west-1.amazonaws.com/s.domain.com/3.png",
i180:"//s3-eu-west-1.amazonaws.com/s.domain.com/4.png",
i220:"//s3-eu-west-1.amazonaws.com/s.domain.com/5.png",
i280:"//s3-eu-west-1.amazonaws.com/s.domain.com/6.png"
}
}
]
});
What is the use of call back function in 'jsonp', should i just trip that off, or am I suppose to use it in some manner. ?
JSON-P is really a JavaScript script that consists of a function call with an argument.
If you want to parse it in PHP, then yes, you need to strip it off. You also need to strip off the );
at the end.
b. How can I rectify the syntax error received in 'jsonp' format ?
You need to fix the data so it really is JSON. The data you have is a JavaScript literal, but it doesn't conform to the subset of JavaScript that matches JSON (e.g. property names are not strings but must be).
It would be better to get a real JSON resource form the source instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With