Jan
Jan

Reputation: 131

Serilaizing in PHP returns wrong value

I try to serialize my data with PHP. Unfortunaly, the serialize() function returns a wrong value.

String to be serialized:

{"2c4cfd9a340dd0dc88b5712c680c1f88":{"type":"product_custom","layout":"default","size":"medium_large","attributes":{"62d7d5184b7a313dc64255bdb8187847":{"type":"image","color":"#FFFFFF","image":"36018"}}}}

What serialize() returns on my server:

serialize($code);

s:204:"{"2c4cfd9a340dd0dc88b5712c680c1f88":{"type":"product_custom","layout":"default","size":"medium_large","attributes":{"62d7d5184b7a313dc64255bdb8187847":{"type":"image","color":"#FFFFFF","image":"36018"}}}}";

What should be returned (https://duzun.me/playground/serialize):

a:1:{s:32:"2c4cfd9a340dd0dc88b5712c680c1f88";a:4:{s:4:"type";s:14:"product_custom";s:6:"layout";s:7:"default";s:4:"size";s:12:"medium_large";s:10:"attributes";a:1:{s:32:"62d7d5184b7a313dc64255bdb8187847";a:3:{s:4:"type";s:5:"image";s:5:"color";s:7:"#FFFFFF";s:5:"image";s:5:"36018";}}}}

Upvotes: 0

Views: 45

Answers (2)

iainn
iainn

Reputation: 17417

The site you're using isn't clear about what it's doing, but it appears to be treating the string as JSON and decoding to an array before serializing it as PHP. If you want to replicate this, you can use:

$str = '{"2c4cfd9a340dd0dc88b5712c680c1f88":{"type":"product_custom","layout":"default","size":"medium_large","attributes":{"62d7d5184b7a313dc64255bdb8187847":{"type":"image","color":"#FFFFFF","image":"36018"}}}}';

echo serialize(json_decode($str, true));

a:1:{s:32:"2c4cfd9a340dd0dc88b5712c680c1f88";a:4:{s:4:"type";s:14:"product_custom";s:6:"layout";s:7:"default";s:4:"size";s:12:"medium_large";s:10:"attributes";a:1:{s:32:"62d7d5184b7a313dc64255bdb8187847";a:3:{s:4:"type";s:5:"image";s:5:"color";s:7:"#FFFFFF";s:5:"image";s:5:"36018";}}}}

As pointed out in the comments, unless there's a specific reason you need serialized PHP, then just stick with the serialized JSON string you already have - it'll be both more readable and portable.

Upvotes: 0

Jeff
Jeff

Reputation: 6953

You need to json_decode it first to get the wanted result:
When you use the boolean switch as second parameter in json_decode it will be an array instead of an object.

$serialized = serialize(json_decode($inputString, true));
echo $serialized;

// output: 
// a:1:{s:32:"2c4cfd9a340dd0dc88b5712c680c1f88";a:4:{s:4:"type";s:14:"product_custom";s:6:"layout";s:7:"default";s:4:"size";s:12:"medium_large";s:10:"attributes";a:1:{s:32:"62d7d5184b7a313dc64255bdb8187847";a:3:{s:4:"type";s:5:"image";s:5:"color";s:7:"#FFFFFF";s:5:"image";s:5:"36018";}}}}

Upvotes: 1

Related Questions