Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

rest - Why does PHP add " " to an empty string?

I’m trying to implement a simple service in PHP. The service needs to return strings to certain requests. However, when I try to echo the string, PHP somehow adds to the beginning of the string. I am using echo to output the response.

I tried to echo one space character:

$test = ' '; 
echo $test;

and in the response I still got ' '.

I have tried header('Content-type: text'); and $string = preg_replace(" ", "", $string);, but I’m still getting the new line in the response.

I’m new to PHP, so if this is some kind of concept, could someone provide me with pointers to information where I can read about it?

question from:https://stackoverflow.com/questions/30709964/why-does-php-add-r-n-to-an-empty-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's possible this character is in your sourcecode somewhere, for instance at the end of one your scripts, like: ?> .

A best practice is to never include the final ?> in each file to avoid accidental output.

This recommendation is in the PSR-2 Coding Style Guide.

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

It's also in the 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...