我有一个带有URL编码符号的查询字符串:
$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
返回一个空字符串。
这是我在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
解析时应该使用哪种编码?
答案 0 :(得分:1)
由于json_encode
仅适用于UTF-8,并且文本位于windows-1251中,因此应将其从该编码转换为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"}
答案 1 :(得分:0)
Try this:
$wm_string = "LMI_MODE=1LMI_PAYMENT_DESC=%CF%EE%E6%E5%F0%F2%E2%EE%E2%E0%ED%E8%E5+Plan+Z";
$wm_string = (parse_url(urldecode($wm_string)));
$wm_string = json_encode(urlencode($wm_string['path']));
echo "JSON: " . $wm_string;
Result:
JSON: "LMI_MODE%3D1LMI_PAYMENT_DESC%3D%CF%EE%E6%E5%F0%F2%E2%EE%E2%E0%ED%E8%E5+Plan+Z"
答案 2 :(得分:0)
我知道这与其他两个答案类似,但只是想指出你不需要而且实际上shouldn't be using urldecode with parse_url。在一个更简单的方法中,你可以解析url字符串并将windows-1251变量转换为utf8。
<?php
$wm_string = "LMI_MODE=1&LMI_PAYMENT_DESC=%CF%EE%E6%E5%F0%F2%E2%EE%E2%E0%ED%E8%E5+Plan+Z+Online";
//Parse the url string
parse_str($wm_string, $args);
//Convert payment description to utf8
$args['LMI_PAYMENT_DESC'] = iconv("windows-1251", "UTF-8", $args['LMI_PAYMENT_DESC']);
echo "JSON: " . json_encode($args, JSON_UNESCAPED_UNICODE);
//JSON: {"LMI_MODE":"1","LMI_PAYMENT_DESC":"Пожертвование Plan Z Online"}