1. The forums will be archived and moved to a read only mode in about 2 weeks (mid march).

How get JSON file

Discussion in 'Development' started by Minto, May 7, 2021.

  1. Minto

    Minto Spider

    Messages:
    6
    GitHub:
    MintoD
    Hi, I want to get json file content from the URL using pocketmine\utils\Internet
     
    Last edited: May 7, 2021
  2. Axon

    Axon Zombie

    Messages:
    276
    Check out the Internet Documentation, you can use `getURL` to fetch a page.
    Then you can convert the string to json.
    Internet Documentation: https://jenkins.pmmp.io/job/PocketM...1b/classpocketmine_1_1utils_1_1_internet.html
    PHP:
    function fetchJson(string $url){
                
    $data = \pocketmine\utils\Internet::getURL($url); // This will get the data on the url
                
    $jsondata json_decode($data); // Convert string to URL
                
    return $jsondata// Returns the Data
            
    }
    Usage:
    PHP:
    $url "https://gist.githubusercontent.com/ErikPDev/e6997ead97591d4d1c703efec26f82af/raw/c7de5291dcdbde8ecb70ed40acadd4e5f0d51557/file.json"// URL
                
    var_dump$this->fetchJson($url) );
     
    Last edited: May 7, 2021
    Agent and Minto like this.
  3. Primus

    Primus Zombie Pigman

    Messages:
    749
    Remind you, that these operations are thread blocking, you must fetch the data either on plugin load or in asynchronous task.
     
    Minto likes this.
  4. Axon

    Axon Zombie

    Messages:
    276
    Agreed!
    Here's a async task
    Usage:
    PHP:
    Server::getInstance()->getAsyncPool()->submitTask(new GetURL("https://gist.githubusercontent.com/ErikPDev/e6997ead97591d4d1c703efec26f82af/raw/c7de5291dcdbde8ecb70ed40acadd4e5f0d51557/file.json"));
    Code:
    PHP:
    <?php
    namespace ErikX\PMMP;

    use 
    pocketmine\scheduler\AsyncTask;
    use 
    pocketmine\Server;
    use 
    pocketmine\utils\Internet;
    use function 
    json_decode;

    class 
    GetURL extends AsyncTask{

        
    /** @var string */
        
    private $URL;
        public function 
    __construct(string $URL){
            
    $this->url $URL;
        }

        public function 
    onRun() : void{
            
    $json Internet::getURL($this->url);
            
            
    $this->setResult(json_decode($json));
        }

        public function 
    onCompletion(Server $server) : void{
            
    $result $this->getResult();
            
    // do something here
            
    var_dump($result);
        }
    }
     
    Agent and Minto like this.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.