2014-09-03 4 views
-1

Итак, я пытаюсь отправить динамическое письмо с 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 protected]", 
        "from_name": "Joe", 
        "to": [ 
        { 
          "email": "[email protected] Joe", 
          "name": "[email protected] Joe" 
        } 
        ], 

        "attachments": [ 

        ] 
      }, 
      "async": false 
    }'; 

Теперь я хочу "html" быть переменной. Поэтому я сделал это

"html": $var, 

К сожалению, это не работает. Не делает {} или использует одинарные кавычки. Есть идеи? Между прочим, он подбирается под струну.

+3

** Никогда ** бросьте свой собственный JSON. Используйте ['json_encode()'] (http://php.net/manual/function.json-encode.php) – Phil

ответ

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 protected]", 
       "from_name": "Joe", 
       "to": [ 
       { 
         "email": "[email protected] Joe", 
         "name": "[email protected] Joe" 
       } 
       ], 

       "attachments": [ 

       ] 
     }, 
     "async": false 
}'; 

Чтобы быть честным с вами, это было бы намного проще, если вы просто использовали массив, а затем кодируются его в JSON с помощью json_encode().

+0

Спасибо, Джон. Вы спасли меня ;) – user302975

1

Как уже упоминалось в моем комментарии, это будет работать намного лучше

$post = [ 
    'key' => 'xxx', 
    'message' => [ 
     'html' => $var, 
     'text' => 'this is the emails text content', 
     'subject' => 'this is the subject', 
     'from_email' => '[email protected]', 
     'to' => [ 
      ['email' => '[email protected] Joe', 'name' => '[email protected] Joe'] 
     ], 
     'attachments' => [] 
    ], 
    'async' => false 
]; 

$postString = json_encode($post); 

Обязательную наследие PHP Примечание: Если вы застряли на PHP версии ниже, чем 5.4, вы, очевидно, не может использовать обозначение сокращенного массива. Замените [] на array(), если это так.

Смежные вопросы