向PHP字符串添加换行符


Adding newline to PHP string

我试图在字符串的末尾添加新行,所以我可以更好地在新行中看到<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));

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

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

' -引号字符串不像" -引号字符串那样支持转义元字符:

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"

"'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));