The Newbie Qs The Newbie Qs - 5 months ago 76
PHP Question

how to parse a json mailgun sendmessage response in php?

Here is my code:

$this->view->assign('mail', $mail);
$mg = new Mailgun($this->getMailgunAPIKey());
$domain = "sandbox1111.mailgun.org";
$res = $mg->sendMessage($domain, array('from' => 'bob@sandbox3445.mailgun.org',
'to' => 'mee@xxxxx.com',
'subject' => $mail->getSubject(),
'text' => $mail->getBody()));
var_dump( $res);


and here is what gets printed out by the var_dump:

object(stdClass)#228 (2) { ["http_response_body"]=> object(stdClass)#223 (2) { ["message"]=> string(18) "Queued. Thank you." ["id"]=> string(52) "<20131211155824.31559.48115@sandbox1111.mailgun.org>" } ["http_response_code"]=> int(200) }


I tried
var_dump( json_decode($res));
but that prints out NULL. How do I access the ["http_response_code"] for instance?

Thanks

ANSWER:

var_dump( $res);
echo LINE.'

';
var_dump( $res->http_response_body );
echo LINE.$res->http_response_code.'

';
echo $res->http_response_body->message.'

';

prints

object(stdClass)#228 (2) { ["http_response_body"]=> object(stdClass)#223 (2) { ["message"]=> string(18) "Queued. Thank you." ["id"]=> string(52) "<20131211161740.16663.18744@sandbox3445.mailgun.org>" } ["http_response_code"]=> int(200) } 150

object(stdClass)#223 (2) { ["message"]=> string(18) "Queued. Thank you." ["id"]=> string(52) "<20131211161740.16663.18744@sandbox3445.mailgun.org>" } 152200

Queued. Thank you.

Answer

Your variable is already json_decoded, with the second parameter to false. json_decode() works with objects by default (default = false in this case), if you want an array, use the 2nd parameter true, see http://php.net/json_decode.

I prefere object notation.

How do I access the ["http_response_code"] for instance?

$res->http_response_body

echo $res->http_response_body->message
//prints "Queued. Thank you."