Skip to content

Instantly share code, notes, and snippets.

@nkcmr
Created August 12, 2015 13:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkcmr/b9b746a52e1627cc01d4 to your computer and use it in GitHub Desktop.
Save nkcmr/b9b746a52e1627cc01d4 to your computer and use it in GitHub Desktop.
<?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
// )
// )
// )
// )
// )
@fpoirier1
Copy link

Exactly what I was looking for! Have done some improvment to the class over the years ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment