Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Temporary fixes while my development machine is borked; felt like sharing...
- // Stolen from various places
- if(!function_exists('json_encode')) {
- function json_encode($data) {
- switch ($type = gettype($data)) {
- case 'NULL':
- return 'null';
- case 'boolean':
- return ($data ? 'true' : 'false');
- case 'integer':
- case 'double':
- case 'float':
- return $data;
- case 'string':
- return '"' . addslashes($data) . '"';
- case 'object':
- $data = get_object_vars($data);
- case 'array':
- $output_index_count = 0;
- $output_indexed = array();
- $output_associative = array();
- foreach ($data as $key => $value) {
- $output_indexed[] = json_encode($value);
- $output_associative[] = json_encode($key) . ':' . json_encode($value);
- if ($output_index_count !== NULL && $output_index_count++ !== $key) {
- $output_index_count = NULL;
- }
- }
- if ($output_index_count !== NULL) {
- return '[' . implode(',', $output_indexed) . ']';
- } else {
- return '{' . implode(',', $output_associative) . '}';
- }
- default:
- return ''; // Not supported
- }
- }
- function json_decode($json, $assoc = false) {
- /* by default we don't tolerate ' as string delimiters
- if you need this, then simply change the comments on
- the following lines: */
- // $matchString = '/(".*?(?<!\\\\)"|\'.*?(?<!\\\\)\')/';
- $matchString = '/".*?(?<!\\\\)"/';
- // safety / validity test
- $json = '';
- $t = preg_replace( $matchString, '', $json );
- $t = preg_replace( '/[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/', '', $t );
- if ($t != '') { return null; }
- // build to/from hashes for all strings in the structure
- $s2m = array();
- $m2s = array();
- preg_match_all( $matchString, $json, $m );
- foreach ($m[0] as $s) {
- $hash = '"' . md5( $s ) . '"';
- $s2m[$s] = $hash;
- $m2s[$hash] = str_replace( '$', '\$', $s ); // prevent $ magic
- }
- // hide the strings
- $json = strtr( $json, $s2m );
- // convert JS notation to PHP notation
- $a = ($assoc) ? '' : '(object) ';
- $json = strtr( $json,
- array(
- ':' => '=>',
- '[' => 'array(',
- '{' => "{$a}array(",
- ']' => ')',
- '}' => ')'
- )
- );
- // remove leading zeros to prevent incorrect type casting
- $json = preg_replace( '~([\s\(,>])(-?)0~', '$1$2', $json );
- // return the strings
- $json = strtr( $json, $m2s );
- /* "eval" string and return results.
- As there is no try statement in PHP4, the trick here
- is to suppress any parser errors while a function is
- built and then run the function if it got made. */
- $f = @create_function( '', "return {$json};" );
- $r = ($f) ? $f() : null;
- // free mem (shouldn't really be needed, but it's polite)
- unset( $s2m ); unset( $m2s ); unset( $f );
- return $r;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement