反序列化真正的转义JSON字符串

时间:2012-02-07 07:33:19

标签: php json serialization

我正在尝试将JSON数据保存到MySQL DB& PHP。我用过

// This is the JSON (from Twitter).
$result = 
Array
(
    [created_at] => Wed, 01 Feb 2012 03:53:25 +0000
    [entities] => Array
        (
            [hashtags] => Array
                (
                    [0] => Array
                        (
                            [text] => somehashtag
                            [indices] => Array
                                (
                                    [0] => 85
                                    [1] => 98
                                )

                        )

                )

$stringForDB = mysql_real_escape_string(serialize($result));

序列化。

我无法将其反序列化。

我试过

$obj=unserialize($stringForDB);

但是$ obj是空白的。

2 个答案:

答案 0 :(得分:0)

尝试

$obj=json_decode($stringForDB);

http://php.net/manual/en/function.json-decode.php

答案 1 :(得分:0)

mysql_real_escape_string会将反斜杠前置为'和',从而无法反序列化。

$serializedResult = serialize($result);

// $stringForDB can not be unserialized since it has extra backslashes
$stringForDB = mysql_real_escape_string($serializedResult));

// Some code to insert $stringForDB into the database

$obj=unserialize($serializedResult);