Question

I am trying to test sending emails using the Mailgun api. I am using PHP to interface with the api. Following is the code that I have tried (from here).

# Include the Autoloader (see "Libraries" for install instructions)
require 'vendor/autoload.php';
use Mailgun\Mailgun;

# Instantiate the client.
$mgClient = new Mailgun('key-3ax6xnjp29jd6fds4gc373sgvjxteol0');
$domain = "samples.mailgun.org";

# Make the call to the client.
$result = $mgClient->sendMessage("$domain",
              array('from'    => 'Excited User <me@samples.mailgun.org>',
                    'to'      => 'Baz <baz@example.com>',
                    'subject' => 'Hello',
                    'text'    => 'Testing some Mailgun awesomness!'));
var_dump($result); 

Now when I try the API, I get a response similar to the following:

stdClass Object ( [http_response_body] => stdClass Object ( [message] => Queued. 
Thank you. [id] => <12345678901234.1234.12345@samples.mailgun.org> )
[http_response_code] => 200 )

How do I assign this output to an array or convert this to simple JSON using PHP? Is there some in-built PHP function which would format the above output to simple JSON or do I need to do something else. I have beginner level PHP skills.

Any help would be very appreciated. Thanks!

P.S.: The mailgun api key used above is from the MailGun API documentation.

UPDATE: Thanks guys. I got it working.

$darr=json_encode($result);
$data=  json_decode($darr,true);

# Prints out the individual elements of the array
echo $data["http_response_body"]["message"]."<br>";
echo $data["http_response_body"]["id"]."<br>";
echo $data["http_response_code"];
Was it helpful?

Solution

You could try the php built-in function json_encode().

http://us3.php.net/json_encode

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top