JSON编码和解码

时间:2012-06-06 02:30:17

标签: php json

我有一个这样的数组:

Array (
    [utm_source] => website
    [utm_medium] => fbshare
    [utm_campaign] => camp1
    [test_cat] => red
    [test_sub] => Category
    [test_ref] => rjdepe
)

json_encode并放入一个cookie。我从cookie中取出它,现在想解码它,但我得到一个空白屏幕。我对于什么是错误感到困惑。对我来说,这个JSON看起来是正确的:

{"utm_source":"website","utm_medium":"fbshare","utm_campaign":"camp1","test_cat":"red","test_sub":"Category","test_ref":"dodere"}

有什么想法吗?

编辑:

我的代码:

$value = array(
    'utm_source' => 'website',
    'utm_medium' => 'fbshare',
    'utm_campaign' => 'camp1',
    'test_cat' => 'red',
    'test_sub' => 'Category',
    'test_ref' => 'rjdepe'
);
$value = json_encode($value);
setcookie("TestCookie", $value, time()+3600);

其他页面:

$cookie = $_COOKIE['TestCookie'];
$cookie = json_decode($cookie);
print_r($cookie);

2 个答案:

答案 0 :(得分:9)

尝试base64_encoding就像这样:

$value = array(
    'utm_source' => 'website',
    'utm_medium' => 'fbshare',
    'utm_campaign' => 'camp1',
    'test_cat' => 'red',
    'test_sub' => 'Category',
    'test_ref' => 'rjdepe'
);
$value = base64_encode(json_encode($value));
setcookie("TestCookie", $value, time()+3600);

其他页面:

$cookie = $_COOKIE['TestCookie'];
$cookie = json_decode(base64_decode($cookie));
print_r($cookie);

答案 1 :(得分:3)

在你之前:

print_r($cookie);

执行:

json_last_error();

它会返回什么吗?如果您得到一个空白屏幕,可能是因为解析器失败,可能是cookie中的json字符串中"的结果被转义\"。 尝试:

$cookie = json_decode(stripslashes($_COOKIE['TestCookie']));

<强>更新

所以我使用了以下代码,并收到了以下输出:

    $value = array(
        'utm_source' => 'website',
        'utm_medium' => 'fbshare',
        'utm_campaign' => 'camp1',
        'test_cat' => 'red',
        'test_sub' => 'Category',
        'test_ref' => 'rjdepe'
    );

    var_dump($value);

    setcookie('TestCookie', json_encode($value), time()+86400);

    echo $_COOKIE['TestCookie'];

    print_r(json_decode($_COOKIE['TestCookie']));

<强>输出

array(6) {
  ["utm_source"]=>
      string(7) "website"
  ["utm_medium"]=>
      string(7) "fbshare"
  ["utm_campaign"]=>
      string(5) "camp1"
  ["test_cat"]=>
      string(3) "red"
  ["test_sub"]=>
      string(8) "Category"
  ["test_ref"]=>
      string(6) "rjdepe"
}

{
    "utm_source":"website",
    "utm_medium":"fbshare",
    "utm_campaign":"camp1",
    "test_cat":"red",
    "test_sub":"Category",
    "test_ref":"rjdepe"
}

stdClass Object
(
    [utm_source] => website
    [utm_medium] => fbshare
    [utm_campaign] => camp1
    [test_cat] => red
    [test_sub] => Category
    [test_ref] => rjdepe
)

如果您注意到,编码是一个数组。 json字符串是一个字符串。解码后的字符串是一个对象。

您可以将此类型转换为数组:

$value = (array) json_decode($_COOKIE['TestCookie']);
// Or
$value = json_decode($_COOKIE['TestCookie'], true);

此外,

根据您的配置,PHP可能会转义cookie中的特殊字符,这似乎是您的JSON解码错误正在传递的内容。

尝试做:

json_decode(str_replace('\"', '"', $_COOKIE['TestCookie']), true);