2016-04-24 78 views
0

我正在使用SendGrid PHP库(https://sendgrid.com/docs/Integrate/Code_Examples/php.html)。访问由SendGrid返回的JSON数据

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

{"message":"success"} 

我可以通过发送一个简单的电子邮件:

<?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); 
?> 

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

PHP-REF view of $res returned by SendGrid

它出现的反应是一个对象 - 大概是JSON?

但是,我无法访问数据,JSON,因为如果我试试这个:

$newtxt = json_decode($res); 

我得到这个错误:

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

如果我试试这个:

$j_array = json_decode($res, true); 

我得到同样的错误。

我可以硬编码 “$ RES” 值:

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

然后工程。

但是,我不能解决如何访问由SendGrid返回的JSON。

我已经试过像各种各样的事情:

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

大概有访问由SendGrid返回所以我可以访问JSON数据JSON的方式。

但我不知道如何?

回答

1

正如您从PHP-REF响应中看到的,$res不是原始JSON。

只需使用$res->getBody()即可访问结果。这会给你从SendGrid解析的JSON。

不要需要json_decode这个。

+0

去吧,谢谢Thomas,非常感谢。 – 4532066