-1

Can some one help me with this problem? i want to get every prefix from every server.

My error: Fatal error: Uncaught TypeError: Cannot access offset of type string on string in test.php:67 Stack trace: #0 {main} thrown in C:\xampp\htdocs\GameServer Status\test.php on line 67

  // JSON string
  $someJSON = https://api.gametools.network/bf1/servers/?name=lo&lang=en-us&region=all&platform=pc&limit=2 (in a URL because of space)

  // Loop through Array
  $someArray = json_decode($someJSON['servers'], true); // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["prefix"];
  }

?>
Lucas
  • 13
  • 1
  • 5

1 Answers1

1

Currently, the $someJSON in your example is just a string containing the URL, you need to call that URL to get the JSON from the API, this can be done easily with the file_get_contents function.

After that, you can decode that JSON with json_decode and then iterate over the servers.

$someJSON = file_get_contents('https://api.gametools.network/bf1/servers/?name=lo&lang=en-us&region=all&platform=pc&limit=2');

$someArray = json_decode($someJSON, true);

foreach ($someArray['servers'] as $key => $value) {
    echo $value["prefix"] . "\n";
}

Optionally you could also use cURL to grab the JSON.

$someJSON = curl_init('https://api.gametools.network/bf1/servers/?name=lo&lang=en-us&region=all&platform=pc&limit=2');

curl_setopt_array($someJSON, [
    CURLOPT_HEADER => 0,
    CURLOPT_RETURNTRANSFER => 1,
]);

$someArray = json_decode(curl_exec($someJSON), true);

curl_close($someJSON);

foreach ($someArray['servers'] as $key => $value) {
    echo $value["prefix"] . "\n";
}
Kim Hallberg
  • 1,165
  • 1
  • 9
  • 18