PHP实现Roblox用户头像设置:用户名转ID及头像URL问题
PHP实现通过Roblox用户名获取头像URL的完整方案
核心流程
要完成需求需分两步调用Roblox官方接口:
- 调用
get-by-username接口,将用户名转换为用户ID - 用获取到的ID调用
avatar-bust接口,生成最终的头像URL
完整代码示例
<?php // 你的用户名列表 $usernames = ["VOICECHAT22983", "测试用户名1", "测试用户名2"]; // 根据用户名获取Roblox用户ID function getRobloxUserId($username) { $requestUrl = "https://api.roblox.com/users/get-by-username?username=" . urlencode($username); $response = file_get_contents($requestUrl); if (!$response) return false; $result = json_decode($response, true); return isset($result['Id']) ? $result['Id'] : false; } // 根据用户ID获取头像URL function getRobloxAvatarUrl($userId) { if (!$userId) return false; $requestUrl = "https://thumbnails.roblox.com/v1/users/avatar-bust?userIds={$userId}&size=150x150&format=Png&isCircular=true"; $response = file_get_contents($requestUrl); if (!$response) return false; $result = json_decode($response, true); return isset($result['data'][0]['imageUrl']) ? $result['data'][0]['imageUrl'] : false; } // 遍历用户名生成头像HTML foreach ($usernames as $username) { $id = getRobloxUserId($username); $avatarUrl = getRobloxAvatarUrl($id); if ($avatarUrl) { echo "<div class='avatar'><img src='{$avatarUrl}' alt='{$username}的头像'></div>"; } else { echo "<div class='avatar'>无法加载{$username}的头像</div>"; } } ?>
避坑要点
- 必须用
urlencode处理用户名,避免特殊字符导致接口请求失败 - 每次接口请求后要先判断响应是否有效,防止JSON解析时报错
- 头像接口返回的是数组结构,需取
data[0]['imageUrl']拿到实际头像地址 - 若服务器禁用
file_get_contents,可替换为CURL版本的请求函数:
function getRobloxUserId($username) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.roblox.com/users/get-by-username?username=" . urlencode($username)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); if (!$response) return false; $result = json_decode($response, true); return isset($result['Id']) ? $result['Id'] : false; }
内容的提问来源于stack exchange,提问作者cdnAshton
相关产品推荐
相关产品推荐

