2

我正在尝试使用 Mailgun api 测试发送电子邮件。我正在使用 PHP 与 api 接口。以下是我尝试过的代码(来自这里)。

# 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); 

现在,当我尝试 API 时,我会收到类似于以下内容的响应:

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

如何将此输出分配给数组或使用 PHP 将其转换为简单的 JSON?是否有一些内置的 PHP 函数可以将上述输出格式化为简单的 JSON,或者我需要做其他事情。我有初级 PHP 技能。

任何帮助将不胜感激。谢谢!

PS:上面使用的 mailgun api 密钥来自 MailGun API 文档。

更新:谢谢大家。我让它工作了。

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

1 回答 1

3

您可以尝试使用 php 内置函数 json_encode()。

http://us3.php.net/json_encode

于 2014-03-11T17:58:19.390 回答