所以我试图用PHP发送动态电子邮件。现在这就是我所拥有的
$postString = '{
"key": "xxx",
"message": {
"html": "this is the emails html content",
"text": "this is the emails text content",
"subject": "this is the subject",
"from_email": "email@email.com",
"from_name": "Joe",
"to": [
{
"email": "Joe@ Joe",
"name": "Joe@ Joe"
}
],
"attachments": [
]
},
"async": false
}';
现在我希望"html"
成为一个变量。所以我做了这个
"html": $var,
可悲的是,这不起作用。不是{}
或使用单引号。有任何想法吗?顺便说一句,它被拾取为一个字符串。
答案 0 :(得分:2)
Variables are not interpolated in strings delimited by single quotes。有几种方法可以解决这个问题。以下示例使用concatenation。
$postString = '{
"key": "xxx",
"html": "' . $var . '",
"message": {
"html": "this is the emails html content",
"text": "this is the emails text content",
"subject": "this is the subject",
"from_email": "email@email.com",
"from_name": "Joe",
"to": [
{
"email": "Joe@ Joe",
"name": "Joe@ Joe"
}
],
"attachments": [
]
},
"async": false
}';
老实说,如果您只使用数组然后使用json_encode()
将其编码为JSON,这将会容易得多。
答案 1 :(得分:1)
正如我的评论中提到的,这会更好用
$post = [
'key' => 'xxx',
'message' => [
'html' => $var,
'text' => 'this is the emails text content',
'subject' => 'this is the subject',
'from_email' => 'email@email.com',
'to' => [
['email' => 'Joe@ Joe', 'name' => 'Joe@ Joe']
],
'attachments' => []
],
'async' => false
];
$postString = json_encode($post);
强制遗留PHP注意事项:如果您坚持使用低于5.4的PHP版本,您显然无法使用简写数组表示法。如果是这种情况,请将[]
替换为array()
。