Shah Rushabh
Shah Rushabh

Reputation: 51

jQuery unserialize data serialized by PHP

How can I unserialize data in jQuery? remember data is Serialized by PHP. Below is given example.

a:2:{i:0;s:9:" img1.jpeg";i:1;s:9:"img2.jpeg";}

Upvotes: 0

Views: 112

Answers (1)

alistaircol
alistaircol

Reputation: 1453

This can be achieved using unserialize and json_encode

$unserialized = unserialize($serialized_from_db);
echo json_encode($unserialized);

But please note your sample provided: s:9:" img1.jpeg" this part is incorrect. The s:9 means it expects string to be 9 bytes (this link provides a good guide on understanding output from serialize), however " img1.jpeg has a space and therefore is 10 bytes and fails: demo failing. You can add a check to see if this failes to unserialize:

if ($unserialized === false)

When you fix the incorrect part to: s:9:"img1.jpeg, giving you:

a:2:{i:0;s:9:"img1.jpeg";i:1;s:9:"img2.jpeg";}

will now work, see demo.

At the end of the day I would recommend as others have above, to store json_encoded values in your database rather than serialized values.

I came up with a really hacky hack to potentially fix bad serialized data:

<?php
function hackFixUnserialized($unserialized_string) {
  $parts = explode(';', $unserialized_string);
  foreach ($parts as &$part) {
    $kv = explode(':', $part);

    if ($kv[0] == 's') {
      $str_without_quotes = str_replace('"', '', $kv[2]);
      if ($kv[1] != strlen($str_without_quotes)) {
        $kv[1] = strlen($str_without_quotes);
      }
    }

    $part = implode(':', $kv);
  }

  return implode(';', $parts);
}

$unserialized_from_db = <<<EOT
a:2:{i:0;s:9:" img1.jpeg";i:1;s:9:"img2.jpeg";}
EOT;

$unserialized = unserialize($unserialized_from_db);
if ($unserialized === false) {
  $hack_fix = hackFixUnserialized($unserialized_from_db);
  printf('bad unserialized, fixed to: %s%s', $hack_fix, PHP_EOL);
  $unserialized = unserialize($hack_fix);

}

echo json_encode($unserialized);

Demo of it here: https://eval.in/783408

Hope this helps

Upvotes: 1

Related Questions