简体   繁体   English

如何在PHP中使用Mojang API

[英]How to use the Mojang API with PHP

The Mojang API allows you to access information related to the Players that play the game. Mojang API允许您访问与玩游戏的玩家相关的信息。 There is a documenation to the API which can be found here . 有一个API的文档,可以在这里找到。 However, since I am not so experienced with using an API , I'd like to know how to grab Username History of a Player. 但是,由于我没有使用API​​的经验,我想知道如何获取播放器的用户名历史记录。 On the Documentation, under UUID -> Name history there is a URL, https://api.mojang.com/user/profiles/<uuid>/names . 在文档上,在UUID -> Name history有一个URL, https://api.mojang.com/user/profiles/<uuid>/names UUID -> Name history https://api.mojang.com/user/profiles/<uuid>/names I know how to get the UUID of a player, and by using the above URL in PHP, I get this output; 我知道如何获取播放器的UUID,并在PHP中使用上面的URL,我得到了这个输出;


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

How do I style this output to make it only show the names of the player? 如何设置此输出的样式以使其仅显示播放器的名称? Here's a link showing what I'd like for it to show: Link 这是一个显示我想要显示的内容的链接: 链接

Here's my code: 这是我的代码:

$username comes from a form on a separate php page. $ 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);

The data is JSON. 数据是JSON。

You can request the data using file_get_contents() (which will, by default, execute a GET request) or cURL for a more advanced way of getting data from an URL. 您可以使用file_get_contents() (默认情况下将执行GET请求)或cURL请求数据,以获取从URL获取数据的更高级方法。

Decoding can be done using json_decode() and reading the properties of the object it creates. 可以使用json_decode()并读取它创建的对象的属性来完成解码。 Also note that I've used urlencode() in case there's special characters in the username. 另请注意,我使用了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"

Let's get a bit more advanced and business-like for just a second in order to increase readability: 为了提高可读性,让我们在一秒钟内获得更高级和业务更新:

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

Usage: 用法:

$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' )

You'd be able to extend this class with new methods if you need to contact other parts of their API. 如果您需要联系其API的其他部分,您可以使用新方法扩展此类。 Simply call $this->callApi() with the URL that comes after https://api.mojang.com/ . 只需使用https://api.mojang.com/之后的URL调用$this->callApi()

For your original question, super simplified: 对于您的原始问题,超简化:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM