I have read lots of different articles on this but can’t seem to find a solution that works.
I’m currently working on getting json data from an API (I have to authorize the connection first) and outputting data from it. (only bits and pieces, like name, id, etc., not the whole thing)
First of all, let me show you my code:
class Connector {
//authorization to the API
public $token;
private $username = 'myuser';
private $password = 'mypassword';
public function __construct() {
$this->getToken();
setcookie ('token', $this->token, time() + 3600, 'https://mycloud.com');
}
public function getToken() {
$url = 'https://auth.mycloud.ch/sso2.php';
$fields = array(
'username' => $this->username,
'password' => $this->password
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
$this->token = json_decode($result, true)['token'];
curl_close($ch);
}
public function getData($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_COOKIE, 'token=' . $this->token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
echo $result->{'id'};
//print_r($result);
}
}
$cnt = new Connector();
$cnt->getData('https://hr.mycloud.ch/services/api/employee/10');
For some reason it can’t output the data when I do echo $result->{‘id’};
It tells me “Trying to get property of non-object”
But I already used json_decode on it…
$this->token = json_decode($result, true)['token'];
When I do print_r($result); it gives me this array:
[{"id":"10","name":"name","employee_id":"id@test.com","user_settings_id":"0","location_id":"1","company_id":"1","active":"1","employee_type":"type_ch"}]
What exactly am I doing wrong? I have also tried it with a foreach loop but it gave me the same error.
I hope you can help me with this, thank you.