JSON使用file_get_contents编码数组

时间:2016-11-08 19:06:07

标签: php json encoding

我正在试图弄清楚如何编码以下内容:

$data[] = '';
//check if real player
if($steam_name != null){
    $data['valid'] = true;
    $data['url'] = "http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=key&vanityurl=$steam_name";
    echo json_encode($data, file_get_contents($data->url));
}else{
    $data['valid'] = false;
    echo json_encode($data);
}

我了解如何获取数据,但似乎没有通过发送。

谢谢!

我的尝试按照下面的答案。这不起作用:

$data[] = '';
//check if real player
if($steam_name != null){
    $data['valid'] = true;
    $url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?';
    $params = [
       'key' => 'key',
       'vanityurl' => $steam_name,
    ];

    $data['url'] = $url . http_build_query($params); 
    echo json_encode($data);

}else{
    $data['valid'] = false;
    echo json_encode($data);
}

1 个答案:

答案 0 :(得分:0)

您应该使用http_build_query()来实现这一目标。

$url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?';
$params = [
   'key' => 'abc123',
   'vanityurl' => $steam_name,
];

$data['url'] = $url . http_build_query($params); 

这将处理参数的正确编码。

此外,此处$data是一个数组,您不能将其称为file_get_contents调用中的对象。我很惊讶你没有得到例外。另外,json_encode doesn't accept parameters like that。试试这个:

// Store the API response in your data array
$data['response'] = file_get_contents($data['url']);

// Return it so you can use it
return json_encode($data);

如果响应是JSON,您可以对其进行解码:

$data['response'] = json_decode(file_get_contents($data['url']));