Mailgun API delivers non-JSON output

Using Mailgun API in PHP returns an object rather than JSON. How can I convert it? Example:

<?php
require 'autoload.php';
use Mailgun\Client as MGClient;

$client = new MGClient('newKey123');
$response = $client->deliverEmail('newdomain.mailgun.org', [
    'sender' => 'Admin <[email protected]>',
    'recipient' => 'User <[email protected]>',
    'subject' => 'Test Message',
    'body' => 'Email conversion test.'
]);

echo json_encode($response);
?>

I had a similar experience where the Mailgun API was returning an object that I needed in JSON format. After some testing, I found that using get_object_vars on the returned object did the trick when simple casting failed. I wrapped the entire output in a function that recursively converts nested objects into associative arrays so that json_encode would process everything properly. Although some third-party libraries have this conversion built in, it’s sometimes necessary to handle it device by device especially when dealing with objects that contain protected properties.

hey, try casting the object to arr using (array)$response then json_encode it. sometimes the mailgun object doesn’t expose properties in the expected way.