更正PHP语法和变量插值邮件()

时间:2013-12-16 01:05:58

标签: php string variables

我有这个代码发送电子邮件:

// create email body and send it - for a domain price offer 
$to = 'user@domain.com';
$email_subject = "$$price offer for $domain";
$email_body =   " $name is offering $$price for $domain \n\n ".
        " Message: $message \n\n ".
        " Contact: $email_address ";

$headers = 'MIME-Version: 1.0' . "\r\n";
//$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: Domain Parking <domainforsale@domain.com>' . "\r\n";
$headers .= 'Reply-To: ' . $email_address . "\r\n";
mail($to,$email_subject,$email_body,$headers);

注意$email_subject$email_body个变量;我正在使用$$price输出$12.34之类的内容。

这是个好主意吗?是否有更好的方法来完成同样的事情?

3 个答案:

答案 0 :(得分:1)

$foo = "bar"; 
echo "$$foo"; //prints $bar

就是这样。使用这种语法会更具可读性:

echo '$' . $foo;

除此之外,您应该阅读http://php.net/manual/en/function.mail.php页面。在其他方面,它指定您应该使用\r\n来分隔标题,而在一些地方使用\n\n

答案 1 :(得分:1)

虽然它有效,但建议改为执行以下操作之一:

$email_subject = '$' . $price . ' offer for ' . $domain;

$email_subject = sprintf('$%s price offer for %s', $price, $domain);

$email_subject = "\$$price offer for $domain";

顺便说一句,mail()可能会为你做这件事,但是你应该清理变量以确保它们不包含换行符。

答案 2 :(得分:0)

我更喜欢使用sprintf()格式化事物:

// create email body and send it - for a domain price offer 
$to = 'user@domain.com';
$email_subject = sprintf("%s offer for %s", $price, $domain);
$email_body = sprintf("%s is offering %s for $domain \n\n ", $name, $price)
            . sprintf(" Message: %s \n\n ", $message)
            . sprintf(" Contact: %s ", $email_address)
            ;

$headers = 'MIME-Version: 1.0' . "\r\n";
//$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: Domain Parking <domainforsale@domain.com>' . "\r\n";
$headers .= 'Reply-To: ' . $email_address . "\r\n";
mail($to,$email_subject,$email_body,$headers);