The Newbie Qs
The Newbie Qs

Reputation: 483

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'    => '[email protected]', 
                            'to'      => '[email protected]', 
                            '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) "<[email protected]>" } ["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?

ANSWER:

  var_dump( $res); 
         echo __LINE__.'<br/><br/>';
         var_dump( $res->http_response_body );
         echo __LINE__.$res->http_response_code.'<br/><br/>';
         echo $res->http_response_body->message.'<br/><br/>';

prints

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

object(stdClass)#223 (2) { ["message"]=> string(18) "Queued. Thank you." ["id"]=> string(52) "<[email protected]>" } 152200

Queued. Thank you.

Upvotes: 1

Views: 2412

Answers (1)

Daniel W.
Daniel W.

Reputation: 32340

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."

Upvotes: 5

Related Questions