Put JSON API output in PHP variable

Asked

Viewed 115 times

1

I am trying to use the following API: http://monitor.sacnr.com/api/? IP=137.74.179.193&Port=7777&Action=info

The question is: how can I put the result of [Players] => 1 in a PHP variable? I just want the value 1, and not [Players] = >.

Through this link, returns the following code:

O:8:"stdClass":18:{s:8:"ServerID";s:5:"53484";s:2:"IP";s:14:"137.74.179.193";s:4:"Port";s:4:"7777";s:8:"Hostname";s:36:"San Andreas Cops And Robbers (SACNR)";s:8:"Gamemode";s:16:"Cops And Robbers";s:8:"Language";s:11:"English/All";s:3:"Map";s:11:"San Andreas";s:10:"MaxPlayers";s:3:"450";s:7:"Players";s:1:"1";s:7:"Version";s:8:"0.3.7-R2";s:8:"Password";s:1:"0";s:4:"Time";s:17:"Thu 08:34, Week 2";s:6:"WebURL";s:13:"www.sacnr.com";s:4:"Rank";s:3:"410";s:10:"AvgPlayers";s:4:"2.68";s:9:"HostedTab";s:1:"0";s:10:"LastUpdate";s:10:"1572022718";s:12:"TotalServers";s:4:"3118";}

The website provides an example code:

<?php require_once("monitor.php"); $monitor = new SACNR\Monitor; echo "<pre>"; print_r($monitor->get_info_by_id(53484)); echo "</pre>"; ?>

Which returns the following:

stdClass Object
(
    [ServerID] => 53484
    [IP] => 137.74.179.193
    [Port] => 7777
    [Hostname] => San Andreas Cops And Robbers (SACNR)
    [Gamemode] => Cops And Robbers
    [Language] => English/All
    [Map] => San Andreas
    [MaxPlayers] => 450
    [Players] => 1
    [Version] => 0.3.7-R2
    [Password] => 0
    [Time] => Thu 08:34, Week 2
    [WebURL] => www.sacnr.com
    [Rank] => 410
    [AvgPlayers] => 2.68
    [HostedTab] => 0
    [LastUpdate] => 1572022718
    [TotalServers] => 3118
)

2 answers

3


You already have the answer with an object mounted by your wrapper, so just access the desired property. See the example below.

<?php 
require_once("monitor.php"); 

$monitor = new SACNR\Monitor; 
$server = $monitor->get_info_by_id(53484);

echo "Usuários online " . $server->Players . "<br />";
echo "Mapa Atual " . $server->Map . "<br />";

0

json is not in a valid format:

O:8:"stdClass":18:{s:8:"ServerID";s:5:"53484";s:2:"IP";s:14:"137.74.179.193";s:4:"Port";s:4:"7777";s:8:"Hostname";s:36:"San Andreas Cops And Robbers (SACNR)";s:8:"Gamemode";s:16:"Cops And Robbers";s:8:"Language";s:11:"English/All";s:3:"Map";s:11:"San Andreas";s:10:"MaxPlayers";s:3:"450";s:7:"Players";s:1:"1";s:7:"Version";s:8:"0.3.7-R2";s:8:"Password";s:1:"0";s:4:"Time";s:17:"Sun 14:04, Week 2";s:6:"WebURL";s:13:"www.sacnr.com";s:4:"Rank";s:3:"414";s:10:"AvgPlayers";s:4:"2.65";s:9:"HostedTab";s:1:"0";s:10:"LastUpdate";s:10:"1572027214";s:12:"TotalServers";s:4:"3147";}

Use this site to validate it : https://jsonformatter.curiousconcept.com/

  • 1

    This is because it is not a JSON, but a serialized object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.