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"];