有效的api请求返回null

时间:2014-10-05 21:28:27

标签: php arrays json api curl

我正在研究RIOT游戏的API。我使用此代码以使其工作:

<?php
    header('Content-Type: text/html; charset=utf-8');
    ini_set("display_errors", "1"); error_reporting(E_ALL);

    $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/Electronic Arts, Legendary, Kiddo?api_key=');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($ch);

        curl_close($ch);

    $json = json_decode($response, true);
     //var_dump($json);
     //$json = array_pop($json);

                echo $json['id'] . ',' . $json['name'] . ',' . $json['summonerLevel'] . "<br/>";
?>

当我直接在我的浏览器中粘贴api调用url时,它将返回:

{
    "kiddo": {
        "id": 35037868,
        "name": "kiddo",
        "profileIconId": 505,
        "summonerLevel": 30,
        "revisionDate": 1412534473000
    },
    "legendary": {
        "id": 229888,
        "name": "Legendary",
        "profileIconId": 592,
        "summonerLevel": 30,
        "revisionDate": 1412259698000
    },
    "electronicarts": {
        "id": 31827832,
        "name": "Electronic Arts",
        "profileIconId": 575,
        "summonerLevel": 30,
        "revisionDate": 1412541482000
    }
}

但是当我执行第一个代码块时,var_dump($json)只返回NULL 我认为必须有一个我无视的简单错误,任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

这与您网址中的空格有关。你需要把%20

/api/lol/euw/v1.4/summoner/by-name/Electronic%20Arts,%20Legendary,%20Kiddo?api_key=

完整的例子

$url = str_replace(' ', '%20', 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/Electronic Arts, Legendary, Kiddo?api_key=');

$ch = curl_init($url);

//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // do not set to false, vunerable to man in the middle attacks
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$resp = curl_exec($ch);

$errno = curl_errno($ch);
$errmsg = curl_error($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

var_dump($errno, $errmsg, $httpcode, $resp);

答案 1 :(得分:0)

在浏览器中粘贴网址,检查是否有效。浏览器对网址进行编码,然后获取结果

在您的代码中使用相同的编码网址,这样可行。