Reading Serialized PHP Objects from Erlang

I started writing some Erlang recently. The vast majority of data I need to access from Erlang resides in cached, serialized php objects. Here's what I came up with to turn a serialized php object into a sort of nested Erlang proplist thing.

<?php $s = array ( 123 , 'hello' , 3.14 , array ( 'a' => 'foo' , 'b' => 'bar' )); print serialize ( $s ); ?>

This gives (wrapped for clarity):

a:4:{i:0;i:123;i:1;s:5:"hello";i:2;d:3.14;i:3;a:2: {s:1:"a";s:3:"foo";s:1:"b";s:3:"bar";}}

It's not hard to see how the (relatively undocumented) PHP serialization format works. Here's what it becomes in Erlang:

php : unserialize ( "a:4:...snip..." ).

{[[{0,123}, {1,<<"hello"> >} , {2,3.14}, {3,[{a,<<"foo"> >} , { b,<< "bar" >>}]}]] , []}

Here's what it does with objects:

<?php class ExampleClass { var $id = 123 ; var $name = "RJ" ; var $languages = array ( 'php' , 'erlang' , 'etc' ); } $s = new ExampleClass (); $ser = serialize ( $s ); print serialize ( $str ); ?>

php : unserialize ( "O:12: \" ExampleClass \" :3:{s:2: \" id \" ;i:123;s:4: \" name \" ;s:2:" " \" RJ \" ;s:9: \" languages \" ;a:3:{i:0;s:3: \" php \" ;i:1;s:6:" " \" erlang \" ;i:2;s:3: \" etc \" ;}}" ). {[{ class , "ExampleClass" , [{ id , 123 }, { name , << "RJ" >> }, { languages ,[{ 0 , << "php" >> }, { 1 , << "erlang" >> }, { 2 , << "etc" >> }]}]}], []}

Due to a combination of PHP's "relaxed" type system, an old database abstraction library, and munging things in and out of memcached, we sometimes end up with numeric properties, such as 'id', represented as strings by PHP. To mitigate this, I ended up with some nasty code that forces certain properties to a predefined type ("id" is always an int, etc..). Yuk. Anyway, here's the Erlang module: