D0vev
D0vev

Reputation: 159

CakePHP 2.x work with JSON response

I am barley new to CakePHP with JSON so please excuse my (maybe) stupid question.

Right now I am trying to handle a JSON respsonse from an external API with the help of an PHP5 Class (Hetzner Robot API) and I am able to view the content with debug() and print_r().

The output looks like this:

Array (
[0] => stdClass Object (
  [server] => stdClass Object (
   [server_ip] => XXX.XXX.XXX.XXX
   [server_number] => XXXXX
   [server_name] => XXXXX
   [product] => EX6
   [dc] => 15
   [traffic] => 30 TB
   [flatrate] =>
   [status] => ready
   [throttled] =>
   [cancelled] =>
   [paid_until] => 2015-05-05
  )
 )
[ 1] => stdClass Object (
  [server] => stdClass Object (
   [server_ip] => XXX.XXX.XXX.XXX
   [server_number] => XXXXXX
   [server_name] => XXXXX
   [product] => EX6
   [dc] => 15
   [traffic] => 30 TB
   [flatrate] =>
   [status] => ready
   [throttled] =>
   [cancelled] =>
   [paid_until] => 2015-05-05
  )
 )

So, I would like to use this information in layout but I might be to stupid to understand the JSON parts the CakePHP 2.x documentation. Would someone please give me a hint where I could find a solution for this?

Upvotes: 1

Views: 116

Answers (1)

robmcvey
robmcvey

Reputation: 815

You'll need to set a variable in your controller as follows;

$json = '{"foo": "bar"}';
$decoded = json_decode($json, true);
$this->set('my_variable', $decoded);

The variable my_variable is now availble in your layout/view.

Upvotes: 1

Related Questions