如何将json数组转换为base64 - php

时间:2018-03-11 09:05:22

标签: javascript php

我有一个将输入转换为base64编码的函数:

function goToMap()
{

 $rows = $('.address');
        $length_rows = $('.address').length;

        $arr_objs = Array();
        $rows.each( function(){

            $obj = {};
            $row_id = $(this).attr('data-id');

            $obj.id = $row_id;
            $obj.address  = $('#address_'+$row_id).val();
            $obj.type     = $('#type_'+$row_id).val();

            $obj.lat      = $(this).attr('data-lat')
            $obj.lnt      = $(this).attr('data-lnt');


            $arr_objs.push($obj);

        });

      $b4 = btoa($arr_objs);

      location.href = 'http:/****/?b4='+$b4;

}

但是当我使用btoa函数将输入转换为base64时,我无法使用json将其转换为纯php

我的base64输出:

W29iamVjdCBPYmplY3RdLFtvYmplY3QgT2JqZWN0XSxbb2JqZWN0IE9iamVjdF0=
用PHP转换后

$all_address = json_decode(base64_decode($gets['b4']),true);
var_dump($all_address);
return;

输出:

string(47) "[object Object],[object Object],[object Object]" 

我的函数的json输出:

[
  {
    "id": "35",
    "address": "تهران  خیابان امام خمینی",
    "type": "1",
    "lat": "35.6886846123666",
    "lnt": "51.387248933315284"
  },
  {
    "id": "91",
    "address": "تهران  خیابان امام خمینی",
    "type": "1",
    "lat": "",
    "lnt": ""
  },
  {
    "id": "36",
    "address": "کرج  کوچه جعفری",
    "type": "2",
    "lat": "35.84001878731047",
    "lnt": "50.93909069895744"
  }
]

1 个答案:

答案 0 :(得分:2)

我用这个功能解决了我的问题:

function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode(parseInt(p1, 16))
    }))
}

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings