【问题标题】:making a jsonp call from within PHP script从 PHP 脚本中进行 jsonp 调用
【发布时间】:2011-07-07 11:29:34
【问题描述】:

我不确定这是否可行,因为我是 PHP 新手。我有一个 URL(例如:http://www.mysite.com/data/response/),它给我一些 cookie 数据作为 json respose( {"cookie_name":"value","ttl":60} )。我有一个 php 脚本,它根据 cookie 值输出一些输出。所以,在这个 php 脚本之上,我需要调用上面的 url,获取 json 响应/解释它并根据响应设置一个 cookie。有人可以帮我解决这个问题吗?

提前非常感谢。 升

【问题讨论】:

    标签: php json


    【解决方案1】:

    这里是:

    $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);
    

    其余代码应该像第一个示例一样工作。希望对您有所帮助!

    【讨论】:

    • 您应该提到,这仅在 allow_url_fopen 设置为 1 时才有效(默认情况下是,但可以禁用)。
    • 如果你想要来自json_decode的关联数组,你需要将第二个参数作为TRUE传递。
    • @cwallenpoole:你是对的,谢谢! @Felix Kling:也感谢您的更新。
    • 非常感谢 WASD42 :) 不幸的是,在我的系统中,甚至“file_get_contents”都以某种方式被禁用,甚至更糟!我无权访问 PHP 配置!
    • @LShetty:不客气!在调用file_get_contents() 之前尝试使用ini_set('allow_url_fopen', 1)
    猜你喜欢
    • 2013-07-28
    • 2012-07-31
    • 2016-11-11
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 2021-12-05
    相关资源
    最近更新 更多