4532066
4532066

Reputation: 2110

Access JSON data returned by SendGrid

I am working with the SendGrid PHP Library (https://sendgrid.com/docs/Integrate/Code_Examples/php.html).

The response is sent ass JSON - e.g. should be something like:

{"message":"success"}

I can send a simple email via:

<?php
$root="../../";
require $root . 'vendor/autoload.php';

$sendgrid = new SendGrid($SendGrid);
$email = new SendGrid\Email();
$email
    //->addTo('[email protected]')
    ->addTo('[email protected]')
    ->setFrom('[email protected]')
    ->setSubject('Subject goes here')
    ->setText('Hello World!')
    ->setHtml('<strong>Hello World!</strong>')
;

$res = $sendgrid->send($email);
?>

When I display the output of $res e.g. using PHP-REF (https://github.com/digitalnature/php-ref) I can see that it looks like this:

PHP-REF view of $res returned by SendGrid

It appears the response is an Object - presumably JSON?

However, I can't access the data as JSON because if I try this:

$newtxt = json_decode($res);

I get this error:

Warning: json_decode() expects parameter 1 to be string, object given in C:\xampp\htdocs\jim\001-jimpix\contact_old\test-send-grid.php on line 24

And if I try this:

$j_array = json_decode($res, true);

I get the same error.

I can hard code the "$res" value as:

$res = "{\"message\":\"success\"}";

And then that works.

However, I can't work out how to access the JSON returned by SendGrid.

I've tried various things like:

$res = json_decode(json_encode($res),TRUE);

Presumably there is a way to access the JSON returned by SendGrid so I can access the JSON data.

But I don't know how?

Upvotes: 0

Views: 344

Answers (1)

Thomas Lomas
Thomas Lomas

Reputation: 1553

As you can see from the PHP-REF response, $res is not the raw JSON.

You can access the result simply by using $res->getBody(). This will give you the parsed JSON from SendGrid.

You do not need to json_decode this.

Upvotes: 1

Related Questions