christopher.web christopher.web - 1 month ago 10
JSON Question

JSON encode an array with file_get_contents

I'm trying to figure out how to encode the following:

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


I understand how to get the data, but it seems to not be sending through.

Thanks!

My attempt as per answer below. This does not work:

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

Answer

You should be using http_build_query() to accomplish that.

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

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

That will handle the proper encoding for the parameters.

Additionally, $data is an array here, you can't call it like an object in your file_get_contents call. I'm surprised you aren't getting an exception. Also, json_encode doesn't accept parameters like that. Try this:

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

If the response is JSON, you can decode it:

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