如何在PHP中使用Mojang API

时间:2015-03-11 13:23:28

标签: php html css api

Mojang API允许您访问与玩游戏的玩家相关的信息。有一个API的文档,可以找到here。但是,由于我对使用API​​不太熟悉,我想知道如何获取播放器的用户名历史记录。在文档的UUID -> Name history下,有一个网址https://api.mojang.com/user/profiles/<uuid>/names。我知道如何获取播放器的UUID,并且通过在PHP中使用上面的URL,我得到了这个输出;


[{"name":"JizzInYaTaco22"},{"name":"_scrunch","changedToAt":1423047892000}]

如何设置此输出的样式以使其仅显示播放器的名称?这是一个链接,显示了我希望它显示的内容:Link

这是我的代码:

$ username来自单独的php页面上的表单。     

$username = $_POST["username"];

// Get the userinfo
$content = file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . urlencode($username));

// Decode it
$json = json_decode($content);


// Save the uuid
$uuid = $json->uuid;
var_dump($json, $json->id, $uuid);
// Get the history (using $json->uuid)
$content = file_get_contents('https://api.mojang.com/user/profiles' . urlencode($uuid) . '/names');

// Decode it
$json = json_decode($content);

$names = array(); // Create a new array

foreach ($json as $name) {
    $names[] = $name->name; // Add each "name" value to our array "names"
}

echo 'UUID: ' . $uuid . '<br />Name history: ' . implode(', ', $names);

1 个答案:

答案 0 :(得分:4)

数据是JSON。

您可以使用file_get_contents()(默认情况下会执行GET请求)或cURL来请求数据,以获取从URL获取数据的更高级方法。

可以使用json_decode()解码并读取它创建的对象的属性。另请注意,如果用户名中有特殊字符,我已使用urlencode()

<?php

$username = $_POST["username"];
$url = "https://api.mojang.com/users/profiles/minecraft/" . urlencode($username);

$content = file_get_contents($url); // Loads data from an URL
// eg. {"id":"360d11df2b1d41a78e1775df49444128","name":"_scrunch"}

$json = json_decode($content);

print_r($json);
/*
 *  stdClass Object
 *  (
 *      [id] => 360d11df2b1d41a78e1775df49444128
 *      [name] => _scrunch
 *  )
 */

var_dump( $json->id ); // string(32) "360d11df2b1d41a78e1775df49444128"
var_dump( $json->name ); // string(8) "_scrunch"

为了提高可读性,让我们在一秒钟之内获得更高级和商业化的内容:

class MojangApi {
    const BASE_URL = 'https://api.mojang.com/';

    public static function getInstance() {
        static $instance;

        if ($instance === null) {
            $instance = new MojangApi();
        }

        return $instance;
    }

    protected function callApi($url) {
        $fullUrl = self::BASE_URL . $url;

        $rawJson = file_get_contents($url);

        return json_decode($rawJson);
    }

    public function getUserInfo($username) {
        return $this->callApi('users/profiles/minecraft/' . urlencode($username));
    }

    public function getNames($uuid) {
        $result = $this->callApi(sprintf('user/profiles/%s/names', urlencode($uuid)));

        $names = array();

        foreach ($result as $singleResult) {
            $names[] = $singleResult->name;
        }

        return $names;
    }
}

用法:

$api = MojangApi::getInstance();

$userInfo = $api->getUserInfo($_POST['username']);

var_dump($userInfo->name); // eg. string(8) "_scrunch"

// ---------------

$usernames =$api->getNames($uuid);

print_r($usernames); // Array ( 'JizzInYaTaco22', '_scrunch' )

如果您需要联系其API的其他部分,您可以使用新方法扩展此类。只需使用$this->callApi()之后的网址https://api.mojang.com/拨打电话即可。

对于您的原始问题,超级简化:

<?php

// Load the username from somewhere
$username = '_scrunch';

// Get the userinfo
$content = file_get_contents('https://api.mojang.com/user/profiles/minecraft/' . urlencode($username));

// Decode it
$json = json_decode($content);

// Check for error
if (!empty($json->error)) {
    die('An error happened: ' . $json->errorMessage);
}

// Save the uuid
$uuid = $json->id;

// Get the history (using $json->uuid)
$content = file_get_contents('https://api.mojang.com/user/profiles/' . urlencode($uuid) . '/names');

// Decode it
$json = json_decode($content);

$names = array(); // Create a new array

foreach ($json as $name) {
    $input = $name->name;

    if (!empty($name->changedToAt)) {
        // Convert to YYYY-MM-DD HH:MM:SS format
        $time = date('Y-m-d H:i:s', $name->changedToAt);

        $input .= ' (changed at ' . $time . ')';
    }

    $names[] = $input; // Add each "name" value to our array "names"
}

echo 'UUID: ' . $uuid . '<br />Name history: ' . implode(', ', $names);