PHP Json_encode将空格更改为加号+ [英] PHP Json_encode changing spaces to plus symbols +

查看:509
本文介绍了PHP Json_encode将空格更改为加号+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序,首先将JSON数据存储在cookie中,然后每隔x秒将其保存到数据库中.它只是打开与服务器的连接,服务器读取cookie.它实际上并没有通过POST或GET发送任何内容.

I have a web app where I first store JSON data in a cookie, then save to the database every x seconds. It just opens a connection to the server, and the server reads the cookie. It doesn't actually send anything via POST or GET.

当我保存到Cookie时,我的数据格式良好.但是,当我在PHP中使用它,然后setcookie一个新的json_encoded数组时,它将用+符号替换空格,然后这些空格将显示在我的Web应用程序中.我找不到禁用json_encode字符串编码的任何方法,也没有找到解析那些加号的JS方法(使用jQuery.parseJSON; stringify的解析也不起作用)...没有人知道:S吗?

While I save to the cookie, my data is formatted fine. However, when I work with it in PHP then setcookie a new json_encoded array, it replaces spaces with + symbols, and then these show up in my web app. I can't find any way to disable encoding of strings for json_encode, nor a JS way of parsing those plus symbols out (using jQuery.parseJSON; stringify's parse didn't work either)... Does anyone have any idea :S?

推荐答案

来自精美手册:

请注意,当您发送cookie时,cookie的值部分将自动进行urlencode,并且在接收到该cookie时,它会被自动解码并通过与cookie名称相同的名称分配给变量.如果您不想这样做,则可以使用setrawcookie(),如果您使用的是PHP 5.

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. If you don't want this, you can use setrawcookie() instead if you are using PHP 5.

但是我认为您仍然希望对Cookie URL进行编码,您只需要%20而不是+即可.但是, urlencode :

But I think you still want the cookie URL encoded, you just want %20 for spaces instead of +. However, urlencode:

[...]由于历史原因,空格被编码为加号(+)

[...] for historical reasons, spaces are encoded as plus (+) signs

您可以尝试使用 rawurlencode 自己进行编码:

You could try using rawurlencode to encode it yourself:

返回一个字符串,在该字符串中,除-_.~以外的所有非字母数字字符均已替换为百分号(%),后跟两个十六进制数字.这是RFC 3986 [...]

Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC 3986 [...]

然后按setrawcookie设置cookie.不幸的是, decodeURI

And then setrawcookie to set the cookie. Unfortunately, none of decodeURI, decodeURIComponent, or even the deprecated unescape JavaScript functions will convert a + back to a space; so, you're probably stuck forcing everyone to make sense the hard way.

这篇关于PHP Json_encode将空格更改为加号+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆