使用PHP将URL编码的字符串编码为JSON [英] Encode URL-encoded string into JSON with PHP
本文介绍了使用PHP将URL编码的字符串编码为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有URL编码符号的查询字符串:
I have a query string with URL-encoded symbols:
$wm_string = "LMI_MODE=1&LMI_PAYMENT_DESC=%CF%EE%E6%E5%F0%F2%E2%EE%E2%E0%ED%E8%E5+Plan+Z";
我需要使用PHP将其转换为JSON,但是json_encode
返回空字符串.
I need to convert it into JSON with PHP, but json_encode
returns an empty string.
这是我在PHP中的代码:
Here is my code in PHP:
parse_str($wm_string, $_REQUEST);
var_dump($_REQUEST);
echo "JSON:".json_encode($_REQUEST);
这是结果:
array(1) { ["LMI_MODE"]=> string(46) "1?LMI_PAYMENT_DESC=Пожертвование Plan Z Online" } JSON:
我该怎么办?
更新:
预期结果是:
{
"LMI_MODE":1,
"LMI_PAYMENT_DESC":"Пожертвование Plan Z Online"
}
UPDATE2:
编码为Windows-1251,而json_encode
似乎期望为UTF-8.有没有办法告诉json_encode
解析时应使用哪种编码?
UPDATE2:
The encoding is windows-1251, while json_encode
seems to be expecting UTF-8. Is there a way to tell json_encode
which encoding it should use while parsing?
推荐答案
由于json_encode
仅适用于UTF-8,并且文本位于Windows-1251中,因此应将其从该编码转换为UTF-8.
Since json_encode
does work with UTF-8 only, and the text is in windows-1251, it should be converted from that encoding to UTF-8.
$wm_string = "LMI_MODE=1&LMI_PAYMENT_DESC=%CF%EE%E6%E5%F0%F2%E2%EE%E2%E0%ED%E8%E5+Plan+Z+Online";
$wm_string = iconv("windows-1251", "UTF-8", $wm_string);
parse_str(urldecode($wm_string), $result);
echo "JSON:".json_encode($result, JSON_UNESCAPED_UNICODE);
输出:
JSON:{"LMI_MODE":"1","LMI_PAYMENT_DESC":"Пожертвование Plan Z Online"}
这篇关于使用PHP将URL编码的字符串编码为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文