大家好,这是 php 中的字符串(抱歉,如果很长)
$JsonSpecificheTitoli='{"titoli":{"TitoloEbay-1-Virtuemart":" Maglia Shirt Adidas Milan tg S M L Per sport d è numerico maniche corte Home ","TitoloEbay-2-EbayIT":" Maglia Shirt Adidas Milan tg M L Ibrahimovic Per sport d è numerico Home ","TitoloEbay-5-EbayIT":" Maglia Shirt Adidas Milan tg XL Per sport d è numerico maniche corte Home ","TitoloEbay-3-EbayDE":" Trikot Shirt Adidas Milan tg S M XL F�r Sport ist numerisch S/S Saison 09 10 ","TitoloEbay-6-EbayDE":" Trikot Shirt Adidas Milan tg L F�r Sport ist numerisch S/S Saison 09 10 Home ","TitoloEbay-4-EbayUK":" Jersey Shirt Adidas Milan tg L XL XXL For sports is numerically Kurze armel "},"specifiche":{"Virtuemart":{"":"Arrivo in 24/48 h con SDA oppure Possibilita di necessita di 4/5 giorni per la spedizione","Maniche":" maniche corte "},"EbayIT":{"":"Arrivo in 24/48 h con SDA oppure Possibilita di necessita di 4/5 giorni per la spedizione","Maniche":" maniche corte "},"EbayDE":{"":"Ankunft in 24/48 h M�glichkeit der SDA oder erfordert 4 / 5 Tage Versandkosten","Arme":" S/S "},"EbayUK":{"":"Arrival in 24/48 h Possibility of SDA or requires 4 / 5 days for shipping","Sleeves":" Kurze armel "}}}';
如果我直接使用 php 从该字符串进行 json_decode 没有问题:
$pr = json_decode($JsonSpecificheTitoli); //-->OK
但是如果我从 REQUEST (来自 Ajax 请求)中获取它,它会给我 null
$Tt = $_REQUEST['Titoli'];
$TtJ = json_decode ($Tt); // --> it says null
$v=json_last_error(); //--> gives me 5 , is Syntax error?
奇怪的是,请求、复制和打印中的相同字符串怎么会使其变坏?
谢谢
最佳答案
$v=json_last_error();
gives me 5 , is Syntax error?
您可以根据 the error constants 进行检查,例如 JSON_ERROR_SYNTAX
,只需回显该值即可:
echo JSON_ERROR_SYNTAX; # 4
echo JSON_ERROR_UTF8; # 5
所以在你的情况下这是一个UTF8错误。 json_decode
Docs 采用 UTF-8 编码字符串作为输入。只要确保它是 UTF-8 编码就可以了。
$_REQUEST
(以及类似的输入变量)的编码取决于发送到您的应用程序的 HTTP 请求(输入)的编码,这取决于原始网站的编码/字符集通常情况下。
没有办法可靠地检测它,所以你最好了解它。但是,如果您需要检测它,mb_http_input
Docs 函数会很有帮助。
获取 PHP 脚本的 HTTP 请求中使用的编码信息,然后根据需要对传入数据进行重新编码,然后再将其传递到 json_decode
中。您可以借助 iconv
functionDocs 或 Multibyte String functionsDocs 重新编码 PHP 中的字符串。
此外,您还可以验证输入是否有效(有效的 UTF-8 字符串),如果不是,则拒绝接受对您的应用程序的无效请求。要检查字符串是否为 UTF-8,您可以对字符串运行正则表达式:
$isUTF8 = preg_match('//u', $string);
关于php - Json 编码从 Ajax 中给我 null,但从正常的 php 字符串中没有给我 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8660164/