We have came across a strange issue while using PHP serialize/unserialize. We have serialized and stored in a particular string in mysql (UTF-8 collation). When unserializing the same it returns error.
Eg: String:
"Anoop did a great job cutting out pictures from the magazine that started with the letter P. "
Serialized data in DB :
s:96:"Anoop did a great job cutting out pictures from the magazine that started with the letter P. ";
While unserializing we got this error Notice - unserialize (): Error at offset 2 of 101 bytes
. We noticed that the string length is different. What would be the cause for this issue.
Any help would be really appreciated. Thanks!
The unserialize() function converts serialized data back into actual data.
unserialize() From the above code, we have a variable with serialized data, $string . We can unserialize the value of the variable using unserialize() function to get back to the original value of the complex array, $myvar. print_r( $newvar );
The best approach is to have normalized table structure (different fields or tables). The next approach is to save data as a delimited string (e.g.: 0,US,1,19 ). Then you can use MySQL's SUBSTRING() or to use standard serialization mechanisms like JSON encode. thats right but the value is not inserted by external app.
serialize is just a built-in, variable handling, PHP function. The counterpart of this is unserialize. You have to save the unserialized data in a variable -> $data=unserialize($serializedData) . After that you can access the data by using the index like $data["name"] for instance.
it is possible that you don't use utf-8 within your connection or your PHP context is not utf-8?
try to use the SQL:
SET CLIENT_ENCODING = utf8
Befor you get your data.
try/verify:
ini_set ('default_charset' , 'UTF-8' );
setlocale (LC_ALL, 'de_DE.UTF-8'); # or what your favorit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With