making a jsonp call from within PHP script
I am not sure if this is even possible since I m new to PHP. I have a URL (for instance: http://www.mysite.com/data/response/) which gives me some cookie data as json respose ( {"cookie_name":"value","ttl":60} ). I have a php script that thows some output based on a cookie value. So, right on top of this php script I need to make a call to the above url, get the json response/interpret it and set a cookie based on the开发者_运维知识库 response. Can someone please help me with this?
Many thanks in advance. L
Here it is:
$url = 'http://www.mysite.com/data/response/';
$result = file_get_contents($url);
$json = json_decode($result, true);
set_cookie('cookie_name', $json['value'], time() + ((int) $json['ttl']));
As cwallenpoole mentioned in comments below, make sure that allow_url_fopen
runtime configuration variable is set to TRUE (it is by default). If not - use ini_set('allow_url_fopen', 1)
, but it may be restricted by safe mode I think :)
json_decode
function has been introduced in PHP 5.2.0. If you have PHP >= 5.2 and json_decode
is not available, please check if JSON extension is enabled (extension=json.so
in your php.ini) and if you PHP was combiled with --disable-json
flag.
If you use pre-5.2 PHP then you can use following code (introduced by Anonymous user on PHP.net):
if ( !function_exists('json_decode') ){
function json_decode($json)
{
$comment = false;
$out = '$x=';
for ($i=0; $i<strlen($json); $i++)
{
if (!$comment)
{
if (($json[$i] == '{') || ($json[$i] == '[')) $out .= ' array(';
else if (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')';
else if ($json[$i] == ':') $out .= '=>';
else $out .= $json[$i];
}
else $out .= $json[$i];
if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
}
eval($out . ';');
return $x;
}
}
If allow_url_fopen
is set to 0 and you cannot change it by ini_set
or by setting it in your php.ini file, that you can stick to cURL (if cURL extension is enabled :)):
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER_HEADER, true);
$result = curl_exec($ch);
curl_close($ch);
The rest code should work as in first example. Hope it helps!
精彩评论