daidai daidai - 7 months ago 21
PHP Question

Unserialize real escaped JSON string

I am trying to save JSON data into a MySQL DB & PHP. I've used

// 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));


to serialize.

I can't unserialize it.

I've tried

$obj=unserialize($stringForDB);


but the $obj is blank.

Answer

mysql_real_escape_string will prepend backslashes to ' and " thus making it impossible to unserialize.

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