Created
August 12, 2015 13:11
-
-
Save nkcmr/b9b746a52e1627cc01d4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
date_default_timezone_set('UTC'); | |
$foo = '{"bar":{"$date":1358205756553},"pop":{"goes":{"err":{"$binary":"c3VyZS4="},"the":{"weasel":{"$date":1358205756553,"$tz":"America/New_York"}}}}}'; | |
class EJSON { | |
protected static $customTypes = []; | |
public static function type($marker, $decoder) { | |
if (!is_callable($decoder)) { | |
throw new \Exception('Type decoder must be callable'); | |
} | |
} | |
public static function decode($data) { | |
if (is_string($data)) { | |
$arr = json_decode($data, true); | |
} else { | |
$arr = $data; | |
} | |
foreach ($arr as $key => &$val) { | |
if (is_array($val)) { | |
if (array_key_exists('$binary', $val)) { | |
echo "'{$key}' is binary data\n"; | |
} else if (array_key_exists('$date', $val)) { | |
echo "'{$key}' is a date\n"; | |
$arr[$key] = new DateTime($val['$date'] / 1000); | |
} else { | |
$arr[$key] = static::decode($val); | |
} | |
} | |
} | |
return $arr; | |
} | |
} | |
$dat = EJSON::decode($foo); | |
print_r($dat); | |
// output | |
// 'bar' is a date | |
// 'err' is binary data | |
// 'weasel' is a date | |
// Array | |
// ( | |
// [bar] => DateTime Object | |
// ( | |
// [date] => 2013-01-14 23:22:36.000000 | |
// [timezone_type] => 3 | |
// [timezone] => UTC | |
// ) | |
// [pop] => Array | |
// ( | |
// [goes] => Array | |
// ( | |
// [err] => Array | |
// ( | |
// [$binary] => c3VyZS4= | |
// ) | |
// [the] => Array | |
// ( | |
// [weasel] => DateTime Object | |
// ( | |
// [date] => 2013-01-14 18:22:36.000000 | |
// [timezone_type] => 3 | |
// [timezone] => America/New_York | |
// ) | |
// ) | |
// ) | |
// ) | |
// ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exactly what I was looking for! Have done some improvment to the class over the years ?