2016-11-08 30 views
1

我试图找出如何编码以下的数组:JSON编码与的file_get_contents

$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); 
} 
+0

乔治,这是JS,我需要知道它是如何通过为好,考虑到它比预期的更thx芽。 –

回答

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'])); 
+0

谢谢!那么我的编码看起来就像'json_encode($ data);'? –

+0

什么是baseurl? –

+0

完成一个答案是正确的,芽。 –