Recently I had to process data in Go that had been previously encoded with PHP’s serialize() function. However, I could not find any libraries that were robust and feature rich enough to handle the decoding. So I created https://github.com/elliotchance/phpserialize.

Here is a simple object encoded as JSON:

{
"foo": "bar",
"baz": 123
}

This same object encoded with PHP’s serialize() function looks like:

O:8:"stdClass":2:{s:3:"foo";s:3:"bar";s:3:"baz";i:123;}

There are a few notable features and drawbacks of serialize():

  1. It can be decoded back into the original object types. Unlike JSON which does not contain this information.
  2. Like JSON it guarantees that the output will be ASCII, even if strings contain multibyte characters. This is important when dealing with UTF-8 strings between systems that may not be able to store multibyte characters or use a different encoding.
  3. One major drawback is it's mostly only useful inside of PHP since the original object names represent builtin and custom classes.
  4. It’s also worth noting that if you are serialising custom classes in PHP you have to be very careful that those classes and the definitions do not change otherwise you may not be able to decode the data again.

Based on the last point it would be uncommon that you need to deal with this outside of PHP, especially in Go… but if you do this library is the answer!

Install / Update


phpserialize requires Go 1.8+.

Example / Usage

To make phpserialize more consistent with other Go encoders (like encoding/json) the serialise() and unserialize() functions are called Marshal() and Unmarshal() respectively.

package main

import (
"github.com/elliotchance/phpserialize"
"fmt"
)

func main() {
out, err := phpserialize.Marshal(3.2, nil)
if err != nil {
panic(err)
}

fmt.Println(string(out))

var in float64
err = phpserialize.Unmarshal(out, &in)

fmt.Println(in)
}

Thanks

I also want to extend a thank you to Armin Ronacher who created the Python library which created many of the tests used in this Go implementation.