新手提问,这里:
我有一个简单的表格,可以返回一个人的姓名,公司和地址。
现在,这些是在不同的行上返回的。如果“公司”字段中没有条目,则发送的电子邮件中会有一个空白行。
我想制作一个IF声明,这样如果“公司”字段中没有条目,那么“地址”将在“名称”之后立即返回而没有额外的空间,但将包括“公司”填写该字段的信息。
PHP代码的相关部分如下所示:
$name = $_POST['name'];
$company = $_POST['company'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$email = $_POST['email'];
$optin = $_POST['optin'];
$comments = ($_POST['comments']);
$body = <<<EOD
Please send samples to:
$name
$company
$address
$city, $state $zip
Email: $email
Opt-In to occasional email list?: $optin
Comments: $comments
EOD;
$headers = "From: $email\r\n";
$success = mail($webMaster, $emailSubject, $body,
$headers);
我真的很感谢你的帮助!
答案 0 :(得分:2)
你必须为此突破HEREDOC,或事先准备好价值,但这很好而且很短:
echo join("\n", array_filter(array($name, $company, $address)));
答案 1 :(得分:0)
我对此进行了编辑,以使用\n
代替<br />
$optin = $_POST['optin'];
$comments = ($_POST['comments']);
$body = "Please send samples to:";
if($_POST['name'] != '') $body .= "\n".$_POST['name'];
if($_POST['company'] != '') $body .= "\n".$_POST['company'];
if($_POST['address'] != '') $body .= "\n".$_POST['address'];
if($_POST['city'] != '') $body .= "\n".$_POST['city'];
if($_POST['state'] != '') $body .= ", ".$_POST['state'];
if($_POST['zip'] != '') $body .= " ".$_POST['zip'];
if($_POST['email'] != '') $body .= "\n\nEmail: ".$_POST['email'];
$body .= "Opt-In to occasional email list?: $optin";
$body .= "\n\nComments: $comments";
$headers = "From: $email\r\n";
$success = mail($webMaster, $emailSubject, $body,
$headers);
答案 2 :(得分:0)
这个怎么样?
$name = $_POST['name'];
//...
if(empty($company)){
$nameAndCompany = $name;
}else{
$nameAndCompany = $name."\n".$company;
}
// or using the ternary operator, because it's a rather simple if
$nameAndCompany = (empty($company))?$name:$name."\n".$company;
$body = <<<EOD
...
$nameAndCompany
$address
$city, $state $zip
...
双引号中的\ n表示换行符。有关ternary operator的更多信息,请参阅php.net文档。
答案 3 :(得分:0)
您在PHP脚本中使用了heredoc语法。你不能在那里使用IF语句。但是你可以使用其他方法:
最简单的方法是第一个(使用另一个答案的array_filter编辑):
$name = $_POST['name'];
$company = $_POST['company'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$email = $_POST['email'];
$optin = $_POST['optin'];
$comments = ($_POST['comments']);
ob_start();
?>
Please send samples to:
<?= implode("\n", array_filter($name, $company, $address)) ?>
<?= $city ?>, <?= $state ?> <?= $zip ?>
Email: <?= $email ?>
Opt-In to occasional email list?: <?= $optin ?>
Comments: <?= $comments ?>
?>
$body = ob_get_clean(); // return the output since ob_start()
$headers = "From: $email\r\n";
$success = mail($webMaster, $emailSubject, $body, $headers);