猿问

如何让这个 PHP 脚本正确显示换行符?

我对 PHP 的理解是,您可以使用“\n”或“\r\n”或echo "<br>";创建一个新行。但是我对它们的应用根本不会创建新行。


我在这里做错了什么?


这是代码:


<?php


session_start(); // before any HTML is echoed

 

if($_POST) {

    //$email = "";

    $email = $_POST['email'];

    $password = $_POST['password'];

     

    if(isset($_POST['email'])) {

        $email = str_replace(array("\r", "\n", "%0a", "%0d"), '', $_POST['email']);

        $email = filter_var($email, FILTER_VALIDATE_EMAIL);        

    }    

    if(isset($_POST['password'])) {

        $password = htmlspecialchars($_POST['password']);

    }

 

    $recipient = "myemail@domain.com";

     

    $headers  = 'MIME-Version: 1.0' . "\r\n"

    .'Content-type: text/html; charset=utf-8' . "\r\n"

    .'From: ' . $email . "\r\n";

 

    $email_content .= "Email: $email" . "\r\n";

    echo "<br />\n";

    $email_content .= "Password: $password";

 

    echo $email_content;

     

    if(mail($recipient, $email_content, $headers)) {

                   header("Location: default-image.png");

                echo "          <script language=javascript>

        //alert('Done, Click Ok');

        window.location='default-image.png';

        </script>";

    } else {

        echo '<p>ERROR! Please go back and try again.</p>';

    }

     

} else {

    echo '<p>Something went wrong</p>';

}

 

?>

感谢您的时间和投入。



哈士奇WWW
浏览 220回答 3
3回答

月关宝盒

您将值分配给变量。不在echo该上下文中,会将您的值输出到您的页面输出。$email_content .= "Email: $email" . "\r\n";$email_content .= "<br />\n";$email_content .= "Password: $password";echo $email_content;这才是正确的做法。接下来是<br />HTML 中新行的表示。\n并且\r\n是新行的 ASCII 表示。例如,这主要用于文本文件和其他编辑器或 CSV 文件。所以你混淆了不同的东西。

扬帆大鱼

使用 \n 清理代码。用于<br />添加分隔线。确保连接<br />到您的变量。\n 将清理源代码视图并<br />需要连接到您的变量。$email_content .= "Email: $email" . "<br />\n";$email_content .= "Password: $password";请注意,如果您不包含 \n,则在浏览器中查看源代码时,您可能会看到 html 可能位于同一行。<?php&nbsp; &nbsp; $email = "foo";&nbsp; &nbsp; $password = "bar";&nbsp; &nbsp; $email_content1 = "";&nbsp; &nbsp; $email_content2 = "";&nbsp; &nbsp; //without the \n to cleanup the source code&nbsp; &nbsp; $email_content1 .= "Email: $email" . "<br />";&nbsp; &nbsp; $email_content1 .= "Password: $password";&nbsp; &nbsp; echo $email_content1;&nbsp; &nbsp; //ignore, used for break&nbsp; &nbsp; echo "\n\n<br />\n\n";&nbsp; &nbsp; //with the \n to cleanup the source code&nbsp; &nbsp; $email_content2 .= "Email: $email" . "<br />\n";&nbsp; &nbsp; $email_content2 .= "Password: $password";&nbsp; &nbsp; echo $email_content2;?>源代码如下所示:Email: foo<br />Password: bar<br />Email: foo<br />Password: bar

慕运维8079593

您应该使用 '\n' 作为将在输出中显示的换行符$email_content .= "Email: $email" . "\n\n\n";$email_content .= "\n\n";$email_content .= "Password: $password";echo $email_content;你会看到密码以新行开头
随时随地看视频慕课网APP
我要回答