这里是:
$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']));
正如下面 cmets 中提到的 cwallenpoole,确保 allow_url_fopen 运行时配置变量设置为 TRUE(默认情况下)。如果没有 - 使用ini_set('allow_url_fopen', 1),但我认为它可能会受到安全模式的限制:)
json_decode 函数已在 PHP 5.2.0 中引入。如果您的 PHP >= 5.2 且 json_decode 不可用,请检查是否启用了 JSON 扩展(您的 php.ini 中的 extension=json.so)以及您的 PHP 是否与 --disable-json 标志结合。
如果您使用 5.2 之前的 PHP,那么您可以使用以下代码(由 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;
}
}
如果 allow_url_fopen 设置为 0 并且您不能通过 ini_set 或在您的 php.ini 文件中设置它来更改它,那么您可以坚持使用 cURL(如果启用了 cURL 扩展 :)):
$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);
其余代码应该像第一个示例一样工作。希望对您有所帮助!