3

我有一个这样的数组:

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

json_encode把它放进饼干里。我从 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);
4

2 回答 2

11

尝试 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);
于 2012-06-07T06:43:19.520 回答
3

在您之前:

print_r($cookie);

做:

json_last_error();

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

$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
)

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

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

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

还,

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

尝试做:

json_decode(str_replace('\"', '"', $_COOKIE['TestCookie']), true);
于 2012-06-06T02:45:33.590 回答