json_encode()输出中的换行符
I am building an output array like so
if (count($errors)) {
$success = 'false';
$output['json_msg'] = "Please try your submission again.";
$output['errors'] = $errors;
} else {
$success = 'true';
$output['json_msg'] = "Thanks for Becoming a NOLA Insider!";
}
$output['success'] = $success;
header('Content-type:application/json;charset=utf-8');
if (count($errors)) { http_response_code(500); }
echo json_encode($output);
exit;
But when I look at the response in Chrome's Network pane of the developer tools I see what appears to be a newline in response:
I tried wrapping json_encode() in trim() but this gave garbled output.
How do I eliminate the carriage return?
我正在构建一个类似的输出数组 p>
if( count($ errors)){
$ success ='false';
$ output ['json_msg'] =“请再次尝试提交。”;
$ output ['errors'] = $ errors;
} else {
$ success ='true';
$ output ['json_msg'] =“感谢成为NOLA Insider!”;
}
$ output ['success'] = $ success;
header('Content-type:application / json; charset = utf-8');
if(count($ errors)){http_response_code(500); }
echo json_encode($ output);
退出;
code> pre>
但是,当我查看开发者工具的Chrome网络面板中的响应时,我看到响应中出现了新行: p >
我尝试在trim()中包装json_encode(),但这会产生乱码输出。 p>
如何消除回车? p>
div>
Do you have a ?>
at the end of your PHP file and what's happening when you remove it ?
Because you may have a carriage return at the end of the script which may be sent before your response :
?>
// END OF FILE
This is explained by the fact that PHP is actually a templating language :
Here is a file which defines a function and which displays a text :
<?php
/**
* @File lib.php
*/
function sayHello()
{
echo "hello";
}
?>
forgotten text
And here is a file that includes this file.
<?php
/**
* @file index.php
*/
include_once('lib.php');
sayHello();
This will output :
forgotten text
hello
The "forgotten text" is output when the lib.php file is included whereas the "hello" is output after.
(But it may be even simpler and just the point that @nanocv suggested)
You can try to remove new line using str_replace
$output = str_replace(array("
", "
", ""),'',$output);
echo json_encode($output);
If you are getting the new line characters like
to your json code after json_encode()
you can follow up the method with the final json_value
that you get. This will remove up all the new lines that has been output-ed from the code that you obtain after you perform the json_encode()
.
Hence you need to preg_replace()
the json outputed value as follows which will remove uo the new lines from the json_code
.
This will replace the new lines with no value over to the second parameter in preg_replace()
.
Try not to provide any white spaced between the
php codes
(i.e) Opening and Closing Codes that you process either at the beginning or at the end of the document. This may cause the issue sometimes.
Code:
$output_json = preg_replace("!?
!","", $output_json);