dongliyan9190 2011-07-19 00:10
浏览 26

PHP的nl2br不工作(也不是替代品)

I'm working on a contact form. The contact message can have line breaks. They need converted to <br>. Nothing is working. Here's my test code:

mail( $email_to, $email_subject,

      '<html><head><title>' . $email_subject . '</title></head><body>'
    . $text_before_message
    . str_replace( array("\\
","\","\
"), "<br />", stripslashes($email_body) )
    . str_replace( array("
","","
"), "<br />", stripslashes($email_body) )
    . nl2br( stripslashes($email_body) )
    . str_replace( array('\\
','\','\
'), "<br />", stripslashes($email_body) )
    . str_replace( array('
','','
'), "<br />", stripslashes($email_body) )
    . stripslashes( nl2br($email_body) )
    . nl2br($email_body)
    . $text_after_message
    . '</body></html>'

    , 'MIME-Version: 1.0' . "
"
    . 'Content-type: text/html; charset=UTF-8' . "
"
    . 'From: ' . $email_from . "
"
    . 'To: ' . $email_to . "
"    
);

When entering:

Test.

Test.

The result in the email is (repeated several times because of the tests):

Test.Test.

Which is spaced with regular line breaks (not <br>) if I look at the source code.

Why is PHP doing this to me? This question appears to be asked a lot, but the solutions I can find... make no difference what-so-ever.

How can I convert the line breaks to html breaks?

  • 写回答

3条回答 默认 最新

  • duanrongpai9556 2011-07-19 02:39
    关注

    Quick answer: use nl2br().

    In other words, it works for me. I prefixed your code with:

    $email_to="...me...";
    $email_from=$email_to;
    $email_subject="HTML test";
    
    $text_before_message='<div style="color:red">BEFORE</div>';
    $text_after_message='<div style="color:red">AFTER</div>';
    $email_body=<<<EOD
    1
    2
    
    3
    
    
    4 (after two blank lines)
    EOD;
    

    In Thunderbird, at least, I see a text email with correct line spacing (for the nl2br() ones). When I view as HTML I also see correct spacing, and the red text at top and bottom.

    It is possible you are using an email client that doesn't understand <br />, and wants to see <br>?! Specifying an explicit doctype might help (but a quick google suggests it won't).

    Debug tip: when everything that should work does not, check doing it manually works. I.e. include a test using a block of static HTML that uses <br /> (and <br>) and see if it works. If it doesn't you know the "which php function do I use" is the wrong question.

    评论

报告相同问题?

悬赏问题

  • ¥20 python忆阻器数字识别
  • ¥15 无法输出helloworld
  • ¥15 高通uboot 打印ubi init err 22
  • ¥20 PDF元数据中的XMP媒体管理属性
  • ¥15 R语言中lasso回归报错
  • ¥15 网站突然不能访问了,上午还好好的
  • ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
  • ¥15 semrush,SEO,内嵌网站,api
  • ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊
  • ¥15 振荡电路,ADS仿真