【问题标题】:Adding newline to PHP string [duplicate]向PHP字符串添加换行符[重复]
【发布时间】:2015-10-22 02:17:58
【问题描述】:

我正在尝试在字符串末尾添加新行,因此我可以更好地在新行中看到<option>,但是我得到的字符串是“\r\n”作为文本而不是新行。代码有什么问题?

foreach ($xml['ROW'] as $ar) {
   $tekstas = $ar['zz'] . ' (' . $ar['xx'] . ')';
   $insert .= '<option value="' . $ar['Adresas'] . '">' . $tekstas .'</option> "\r\n"' ;
}
echo nl2br(htmlentities($insert));

【问题讨论】:

    标签: php html


    【解决方案1】:

    差不多了,看看将新行连接到您生成的字符串的其余部分的正确方法。

    foreach ($xml['ROW'] as $ar) {
     $tekstas = $ar['zz'] . ' (' . $ar['xx'] . ')';
     $insert .= '<option value="' . $ar['Adresas'] . '">' . $tekstas   .'</option> ' . PHP_EOL ;
    }
    echo nl2br(htmlentities($insert));
    

    【讨论】:

    • \r\n 用于 Windows,\n 用于基于 UNIX 的系统。如果您使用常量PHP_EOL,它将在两者上更加兼容。
    【解决方案2】:

    '-quoted 字符串不支持转义的元字符,如 "-quoted 的:

    echo '\r' - outputs a literal backslash and an 'r'
    echo "\r" - outputs a carriage return
    

    ' 字符串中支持的唯一转义符是 \' 和 \\。

    所以..

    '</option> "\r\n"' 
    ^---open single quote string
                     ^---close single-quote string
    

    应该是什么时候

    '</option> ' . "\r\n"
    

    改为。

    【讨论】:

      【解决方案3】:

      "\r\n" 应该用双引号引起来。

      foreach ($xml['ROW'] as $ar) {
         $tekstas = $ar['zz'] . ' (' . $ar['xx'] . ')';
         $insert .= '<option value="' . $ar['Adresas'] . '">' . $tekstas .'</option>'."\r\n";
      }
      echo nl2br(htmlentities($insert));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-12
        • 2019-12-05
        • 2017-11-28
        • 2016-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-20
        相关资源
        最近更新 更多