Search code examples
phpcodeigniter-2

How do I use response from an API into the controller - CodeIgniter


I tried to integrate an API that built-in laravel and now I have to use that API's response into the Codeigniter project, I'm developing a Codeigniter project(I'm not familiar with this framework and it's my first time working with this),

I finally could do it, I'm getting a response from an API

        $result = curl_exec($response); 
        $rs=json_decode($result,true); print_r($rs);
        return $rs;

        Array( 
             [user] => 
                  Array( 
                       [user_no] => PMRQ3fVd6eGEvd5aO9MDJg()() [name] => Anthony [middle_name] => S [lastname] => Mosteller [email] => AnthonyMosteller@test.net
              )
        )

and desperately trying to access the object full name, email, and user_no into my controller But I am stuck now.

controller code:

$user=$this->userapi->userapicall($user_url,$token); 
$this->session->set_userdata('username',$user['name']); // here want to use full name (name+middle_name+lastname)
$this->session->set_userdata('useremail',$user['email']);

I'm getting an error for name and email

A PHP Error was encountered Severity: Notice

Message: Undefined index: name

Filename: controllers/auth.php

Line Number: 106

Do I need to create for each loop or seems something really silly mistake I make

I would appreciate an example of this.


Solution

  • $rs = json_decode($result,true); print_r($rs);

    Here you are getting a multidimensional array. As per your code sample it looks like -

    $rs = ['user' => ['user_no' => 'PMRQ3fVd6eGEvd5aO9MDJg', 'name' => 'Anthony', 'middle_name' => 'S', 'lastname' => 'Mosteller', 'email' => 'AnthonyMosteller@test.net']];

    So if are trying to access user's name in controller -

    $this->session->set_userdata('username',$user['user]['name']);
    

    This should fix the problem. Also you should check if you are getting success status from API.