访问SendGrid返回的JSON数据

时间:2016-04-24 15:52:58

标签: php json sendgrid

我正在使用SendGrid PHP库(https://sendgrid.com/docs/Integrate/Code_Examples/php.html)。

响应发送给JSON - 例如应该是这样的:

{"message":"success"}

我可以通过以下方式发送简单的电子邮件:

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

$sendgrid = new SendGrid($SendGrid);
$email = new SendGrid\Email();
$email
    //->addTo('you@me.com')
    ->addTo('you@me.com')
    ->setFrom('me@bar.com')
    ->setSubject('Subject goes here')
    ->setText('Hello World!')
    ->setHtml('<strong>Hello World!</strong>')
;

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

当我显示$ res的输出时,例如使用PHP-REF(https://github.com/digitalnature/php-ref)我可以看到它看起来像这样:

PHP-REF view of $res returned by SendGrid

看来响应是一个对象 - 大概是JSON?

但是,我无法以JSON身份访问数据,因为如果我尝试这样做:

$newtxt = json_decode($res);

我收到此错误:

  

警告:json_decode()期望参数1为字符串,对象在第24行的C:\ xampp \ htdocs \ jim \ 001-jimpix \ contact_old \ test-send-grid.php中给出

如果我试试这个:

$j_array = json_decode($res, true);

我得到了同样的错误。

我可以硬编码&#34; $ res&#34;价值为:

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

然后就行了。

但是,我无法解决如何访问SendGrid返回的JSON。

我尝试了各种各样的事情:

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

据推测,有一种方法可以访问SendGrid返回的JSON,因此我可以访问JSON数据。

但我不知道怎么做?

1 个答案:

答案 0 :(得分:1)

从PHP-REF响应中可以看出,$res不是原始JSON。

您只需使用$res->getBody()即可访问结果。这将为您提供SendGrid中解析的JSON。

需要json_decode这个。