StoneSmith StoneSmith - 1 year ago 110
JSON Question

After Encodeing json i have and extra whitespace, how can i remove that?

i have the following array whitch i want to encode to jSon:

$output = array("success" =>0,"msg" => "The e-mail address is already in use");

I am useing the following method to encode:

echo json_encode($output);

As a result I get back the following string:

{"success":0,"msg":"The e-mail address is already in use"}

I seems perfectly okey but I have an extra whitespace at the end witch prevent me for useing the jSon string any further. Can anyone help me how to remove this whitespace from the end?

Answer Source

Likely you have some content after an ending PHP tag. As an example:

    $output = array("success" =>0,"msg" => "The e-mail address is already in use");
    echo json_encode($output);

Now I cant represent a new line in the code block but assume the \n is a line return. Now after the PHP tags it will echo the json, and then after PHP tags it echos any content such as that new line. You can however just remove the end tag. This is also true of the open tag and any content there will likewise be output, but that one is much easier to spot if its at the top of the file.

Or at least that's my best guess if you have {...}\n as your json output.

It's an extremely easy mistake to make that can be hard to spot. It may seem strange, but it does happen like this.

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