-1

API code from a template:

$country_array = array();
$country_array['data'] = array();

while($row = $result->fetch(PDO::FETCH_ASSOC))
{
    extract($row);

    $country_item = array
    (
        'ID' => $ID,
        'Name' => $Name,
        'Population' => $Population,
        'Area' => $Area,
    );

    // Push to "data"
    array_push($country_array['data'], $country_item);
}

// Turn to JSON and output

echo json_encode($country_array);

JSON data:

{"data":
   [{"ID":"1","Name":"Portugal","Population":"10286263","Area":"92212"},
    {"ID":"2","Name":"United Kingdom","Population":"66836327","Area":"242495"}]}

I am not sure how to go about storing this data in PHP.

Here's what I have so far:

$response = file_get_contents('http://127.0.0.1/100520093/api/post/read.php');
$response = json_decode($response);

echo $response

The above results in an error message saying I cannot convert an object of Class stdClass to String.

Following the examples in W3Schools results in "data => Array".

Any help is appreciated, I'm still an amateur, so please go easy on me if this is an overly asked question, I could not find anything related to my particular case.

Barmar
  • 741,623
  • 53
  • 500
  • 612
MagorTuga
  • 33
  • 6
  • Why do you need to do `extract($row)`? Isn't `$country_item` the same as `$row`? – Barmar May 13 '21 at 00:14
  • Use the `true` second argument to `json_decode()` to make it return an associative array instead of object. And use `var_dump()` instead of `echo`, since you can only echo strings and numbers. – Barmar May 13 '21 at 00:16

1 Answers1

0

By default, json_decode() decodes JSON objects as PHP StdClass objects. Using a second argument true makes it decode them as associative arrays instead.

When you try to echo something, it's converted to a string first. Arrays are converted to just the word Array. Objects can't be converted to strings unless the class provides a magic method for it, so you get an error.

Instead, use var_dump() or print_r() to show the contents.

$response = file_get_contents('http://127.0.0.1/100520093/api/post/read.php');
$response = json_decode($response, true);

var_dump($response);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you, this is perfect, but now how do I go about storing these values? Again, I'm sorry for the noob questions. – MagorTuga May 13 '21 at 00:25