How to handle Mailgun API response in JSON format using PHP

I’m currently trying to send emails via the Mailgun API using PHP, but I’m running into an issue with the output format. When I send a request, I receive a response as a stdClass object instead of a straightforward JSON object that I can easily work with.

Here’s the PHP code I’m using:

require 'vendor/autoload.php';
use Mailgun\Mailgun;

$mailgunClient = new Mailgun('key-abc123def456ghi789');
$domainName = "example.mailgun.org";

$response = $mailgunClient->sendMessage("$domainName", [
    'from' => 'Demo User <[email protected]>',
    'to' => '[email protected]',
    'subject' => 'Hello from Mailgun!',
    'text' => 'This is just a sample testing email from Mailgun.'
]);

print_r($response);

The response I’m getting looks like this:

stdClass Object (
    [http_response_body] => stdClass Object (
        [message] => Queued. Thank you.
        [id] => <[email protected]>
    )
    [http_response_code] => 200
)

I’m trying to pull out specific data such as the message and ID from the response. Is there a straightforward way to convert this object into a usable format? I’m still getting accustomed to PHP, so I would appreciate any simple guidance.

UPDATE: I managed to find a solution! You can convert the object as follows:

$jsonFormat = json_encode($response);
$responseArray = json_decode($jsonFormat, true);

echo $responseArray["http_response_body"]["message"] . "\n";
echo $responseArray["http_response_body"]["id"] . "\n";
echo $responseArray["http_response_code"];

Your solution works, but there’s a simpler way without the double conversion. You’re already working with a stdClass object, so just access the properties directly:

echo $response->http_response_body->message . "\n";
echo $response->http_response_body->id . "\n";
echo $response->http_response_code;

Skip the json_encode/json_decode dance - it’s unnecessary and slower. stdClass objects let you access nested properties just like arrays, but with object syntax. I’ve used Mailgun’s API for years and this direct approach works great in production.

You can also use get_object_vars() if you want array-like access without the JSON conversion overhead. Just do $responseData = get_object_vars($response->http_response_body) and you’ll get direct array access without serialization. I’ve used this a lot when building wrapper functions around Mailgun responses - it keeps the original data types but gives you array notation flexibility. Make sure to check that http_response_code is 200 first though, or you’ll get undefined property errors on failed requests.

both work fine, but if you need an actual json string for logging or storage, go with your original method. converting stdclass to json makes it way easier to save responses to files or databases compared to working with raw objects.