1

I made an API call and received the response in JSON format.

JSON:

{
  "Specialities": [
    {
      "SpecialityID": 1,
      "SpecialityName": "Eye Doctor"
    },
    {
      "SpecialityID": 2,
      "SpecialityName": "Chiropractor"
    },
    {
      "SpecialityID": 3,
      "SpecialityName": "Primary Care Doctor"
    }
  ]
}

Controller File:

public function index(){
      $data= json_decode(file_get_contents('some_url'));
      $this->load->view('my_view',$data);
}

Above code doesn't work because in view I can't access the nested object properties. However I am able to echo the JSON properties in controller file just like this:

Controller File:

public function index(){

     $data=json_decode(file_get_contents('some_url'));
     foreach ($data as $key=>$prop_name){
        for($i=0;$i < count($prop_name);$i++){
          echo $prop_name[$i]->SpecialityID;
          echo $prop_name[$i]->SpecialityName;
        }
     }
}

My question is how do I pass this JSON to view and how can I access those properties in view file?

Sidra
  • 111
  • 2
  • 9
  • 1
    you need to pass data in array to `VIEW` like ===> `$data['myJson'] = json_decode(file_get_contents('some_url')); $this->load->view('my_view', $data);` – Noman Sep 20 '16 at 12:12
  • For better understanding you can see this link to read data in view http://stackoverflow.com/questions/9446700/codeigniter-passing-data-from-controller-to-view?answertab=votes#tab-top – Noman Sep 20 '16 at 12:14

2 Answers2

2

In controller changes like

public function index(){
      $data['json_data']= json_decode(file_get_contents('some_url'));
      $this->load->view('my_view',$data);
}

and in the view

echo "<pre>";print_r($json_data);
dev
  • 496
  • 1
  • 5
  • 18
0

As per Docs

Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading method.

Here is an example using an array:

So you need to change your code in controller

Controller.php

$data = array();
$data['myJson'] = json_decode(file_get_contents('some_url'));
$this->load->view('my_view',$data);

my_view.php

<html>
....
<?php 
//Access them like so
print_r($myJson);
// Rest of your code here to play with json 
?>
....
</html>
Community
  • 1
  • 1
Noman
  • 4,088
  • 1
  • 21
  • 36