php - 为什么 PHP 将 "\r\n"添加到空字符串中?

标签 php rest request

我正在尝试用 PHP 实现一个简单的服务。服务需要向某些请求返回字符串。但是,当我尝试回显字符串时,PHP 会以某种方式将 \r\n 添加到字符串的开头。我正在使用 echo 来输出响应。

我尝试回显一个空格字符:

$test = ' '; 
echo $test;

在响应中我仍然得到 '\r\n'.

我试过 header('Content-type: text');$string = preg_replace("\r\n", "", $string);,但我仍然在响应中收到新行。

我是 PHP 新手,所以如果这是某种概念,有人可以提供我可以阅读的信息指针吗?

最佳答案

这个字符可能在您的源代码中某处,例如在您的脚本的末尾,例如:?>\r\n .

最佳做法是永远不要包含最后的 ?>在每个文件中以避免意外输出。

此建议位于 PSR-2编码风格指南。

The closing ?> tag MUST be omitted from files containing only PHP.

它也在 manual 中.

If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

关于php - 为什么 PHP 将 "\r\n"添加到空字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709964/

相关文章:

python-3.x - Python 3.6 urllib 为什么行以 b 开头

javascript - 如何在 php 语言(或 javascript)上将 InDesign 文件与 XML 标签文件粘合?

web-services - 我应该坚持使用 axis2c 还是转向 apache wink?

java - Magento - 通过休息创建订单

javascript - 刷新 $http Promise 返回的数据

grails - 如何在grails中实现请求超时?

javascript - PhantomJS 上的阻止请求

php - Ubuntu 更改 sudo php 路径

php - 从表中选择日期为 3 个月后的记录

java - MVC 模型应该抽象到什么程度?