cli-server is a script utilizing PHP’s inbuilt server (only available in PHP >= 5.4), designed for developmental and test purposes only - it’s not designed to replace a web server. It’s severely limited in functionality [1 request at a time, etc.]
I wouldn’t do this kind of thing at all because this piece of code implies you are going to output pieces of data - either to the browser or to CLI - and delimit them with line breaks. The problem is that when outputting to a browser you will need to run your data through htmlspecialchars() in order to be able to print all characters and avoid weird stuff going on when <, > or & is outputted (CLI doesn’t need this). Then you will have to have another PHP_SAPI condition somewhere else in your code and this logic will get scattered in different places.
I’d suggest doing it in 2 separate and independent steps - first prepare your text using simple \n newlines and then format it for desired output. For CLI: if PHP_EOL is \n you can output the text as it, otherwise you can replace \n with PHP_EOL. For HTML you run the text through nl2br(htmlspecialchars($text)) - this will ensure proper rendering of all characters and combinations of them (almost - in HTML you may need to add a white-space css rule if you want multiple spaces to be rendered like in CLI):
// $text uses \n as newlines
function outputText($text) {
if (PHP_SAPI == 'cli') {
if (PHP_EOL != "\n") {
$text = str_replace("\n", PHP_EOL, $text);
}
echo $text;
} else {
echo nl2br(htmlspecialchars($text));
}
}
Or, you can do it line by line:
// $line is one line of text excluding newline
function outputLine($line) {
if (PHP_SAPI == 'cli') {
echo $line . PHP_EOL;
} else {
echo htmlspecialchars($line) . "<br />\n";
}
}