2016-04-24 93 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