1

I have this PHP class for an API:

class Integra {
    public function __construct()
    {
        $this->api_key = 'API-XXXXXXX';
        $this->api_salt = '';
    }

    public function build_query($type, $data = array())
    {
        //$salted = hash_hmac('md5', $this->api_key, $this->api_salt);

        //$data['api_key'] = $salted;
        //$data['key'] = $this->api_key;
        $params = $data;

        $data_string = json_encode($params);  

        $ch = curl_init('http://domain.com/api.php');                                                               
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json')
        );

        $response = curl_exec($ch);
        curl_close($ch);

        $response = json_decode($response);

        return $response;
    }
}

so this is posting data to the relevant page/function.

I want to be able to return the data as objects, i have tried the following on the page that the data is being posted to but nothing is being returned.

What have i done wrong?

<?php
return array('status' => 'test', 'reason' => 'test2');
?>

Here is how i call the class and function:

$Integra = new Integra();
$output = $Integra->build_query('check_system.php');

echo $output->reason;
echo $output->status;

1 Answer 1

1

You can type cast it to object after initializing the array.

return (object) array('status' => 'test', 'reason' => 'test2');

https://3v4l.org/dKWAT

Sign up to request clarification or add additional context in comments.

10 Comments

i am getting this error: Notice: Trying to get property of non-object in /home/sites/pjford.co.uk/public_html/test.php on line 46 Notice: Trying to get property of non-object in /home/sites/pjford.co.uk/public_html/test.php on line 47
Dump the variable $response (the freshly json decoded one) and look what you really get from the API.
Dump the return of curl_exec(), you may know then what is wrong.
I just noticed you have in $this->domain domain.com/api and when you initialize curl, you fill it with $this->domain.'/api/' . $type which makes it domain.com/api/api/$type, I think it should just be $this->domain.'/' . $type.
check my update, i have just made a change so its posting directly to one page, its still returning the same error
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.