jerrygarciuh jerrygarciuh - 1 year ago 107
PHP Question

newline in json_encode() output

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;

if (count($errors)) { http_response_code(500); }
echo json_encode($output);

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:

developer console screenshot

I tried wrapping json_encode() in trim() but this gave garbled output.

How do I eliminate the carriage return?

Answer Source

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 :


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 :

 * @File lib.php
 function sayHello()
     echo "hello";
 forgotten text

And here is a file that includes this file.

 * @file index.php

This will output :

forgotten text

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download