PHP serialize() and unserialize() Implemented In Go

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

Here is a simple object encoded as JSON:

"foo": "bar",
"baz": 123

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


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

go get -u

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 mainimport (
func main() {
out, err := phpserialize.Marshal(3.2, nil)
if err != nil {
fmt.Println(string(out)) var in float64
err = phpserialize.Unmarshal(out, &in)


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.

Originally published at on August 20, 2017.

Written by

I’m a data nerd and TDD enthusiast originally from Sydney. Currently working for Uber in New York. My thoughts here are my own. 🤓

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store