Skip to content

Instantly share code, notes, and snippets.

@xkr47
Last active February 16, 2016 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xkr47/1db1d70895e618484bea to your computer and use it in GitHub Desktop.
Save xkr47/1db1d70895e618484bea to your computer and use it in GitHub Desktop.
PHP serialized object format <-> YAML converter

These scripts convert PHP serialized object format e.g.

a:2:{i:2;a:4:{s:5:"title";s:5:"Hello";s:5:"count";i:0;s:12:"hierarchical";i:0;s:8:"dropdown";i:0;}s:12:"_multiwidget";i:1;}

to YAML format:

---
2:
  title: Hello
  count: 0
  hierarchical: 0
  dropdown: 0
_multiwidget: 1
...

YAML was chosen over JSON because JSON loses type information and serializes everything as strings while YAML seems to support at least the datatypes I needed :)

The yaml php lib is not installed by default, see the install-deps-debian.sh file for installation script for Debian/Ubuntu.

After that you can use the php2yaml and yaml2php scripts for conversion.

Example:

echo 'a:2:{i:2;a:4:{s:5:"title";s:5:"Hello";s:5:"count";i:0;s:12:"hierarchical";i:0;s:8:"dropdown";i:0;}s:12:"_multiwidget";i:1;}' > foo.phpobj
./php2yaml < foo.phpobj > foo.yaml
# edit foo.yaml
./yaml2php < foo.yaml > foo.phpobj
cat foo.phpobj

It works even if the php serialization contains embedded linefeeds. No idea about other control characters.

The scripts exit with error code 1 if input cannot be parsed.

#!/bin/bash
set -ex
apt-get install libyaml-dev php-pear php5-dev
pecl install yaml-1.2.0
patch /etc/php5/cli/php.ini <<EOF
--- /etc/php5/cli/php.ini~ 2015-10-04 19:23:22.000000000 +0300
+++ /etc/php5/cli/php.ini 2016-02-16 20:18:05.703061531 +0200
@@ -870,6 +870,9 @@
; default extension directory.
;
+; xkr47
+extension=yaml.so
+
;;;;;;;;;;;;;;;;;;;
; Module Settings ;
;;;;;;;;;;;;;;;;;;;
EOF
#!/usr/bin/php5
<?php
$obj = unserialize(trim(file_get_contents("php://stdin")));
if ($obj === false) exit(1);
print(yaml_emit($obj));
?>
#!/usr/bin/php5
<?php
$obj = yaml_parse(trim(file_get_contents("php://stdin")));
if ($obj === false) exit(1);
print(serialize($obj));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment