在简单的引号PHP中插入一个变量
问题描述:
How i can use a variable ($_REQUEST('subject')) inside simple quotation marks. This is my code:
<?php
$uri = 'https://mandrillapp.com/api/1.0/messages/send.json';
$postString = '{//i can't quit this quotation mark
"key": "myapi",
"message": {
"html": "this is the emails html content",
"subject": "$_REQUEST['subject'];",//this dont work
"from_email": "email@mydomain.com",
"from_name": "John",
"to": [
{
"email": "test@hotmail.com",
"name": "Bob"
}
],
"headers": {
},
"auto_text": true
},
"async": false
}';
?>
答
change "subject": "$_REQUEST['subject'];"
to "subject": "' . $_REQUEST['subject'] . '"
答
Try this:
$postString = '{
"key": "myapi",
"message": {
"html": "this is the emails html content",
"subject": "'.$_REQUEST['subject'].'", // Modify this way
"from_email": "email@mydomain.com",
"from_name": "John",
....
.....
}';
答
That's JSON! Use json_encode and json_decode!
$json = json_decode ($postString, true); // true for the second parameter forces associative arrays
$json['message']['subject'] = json_encode ($_REQUEST);
$postString = json_encode ($json);
Although, it looks like you could save a step and yourself some trouble if you just build $postString
as a regular php array.
$postArr = array (
"key" => "myapi",
"message" => array (
"html" => "this is the emails html content",
"subject" => $_REQUEST['subject'],
"from_email" => "email@mydomain.com",
"from_name" => "John",
"to" => array (
array (
"email" => "test@hotmail.com",
"name" => "Bob"
)
),
"headers" => array (),
"auto_text" => true
),
"async" => false
);
$postString = json_encode ($postArr);