PHP兼容低版本和高版本的json数据处理类
json数据格式是当下比较流行的一种, 比起xml来,json格式更易用简单. 同时,与javascript配合起来可以说是最佳的数据交换格式. 在php 5.2以上版本,已经支持json的解析了,但是在php 5.2一下就不被支持了. 下面这个类可以实现兼容json_encode函数, 在高版本上,使用自带函数解析,低版本使用自定义函数解析,相信这种功能对PHP开发者来说很实用.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
/* * 作者: 雪狐博客 */ final class Json { static public function encode( $data ) { if (function_exists( 'json_encode' )) { return json_encode( $data ); } else { switch ( gettype ( $data )) { case 'boolean' : return $data ? 'true' : 'false' ; case 'integer' : case 'double' : return $data ; case 'resource' : case 'string' : return '"' . str_replace ( array ("\r ", " \n ", " < ", " > ", " & "), array('\r', '\n', '\x3c', '\x3e', '\x26'), addslashes($data)) . '" '; case 'array' : if ( empty ( $data ) || array_keys ( $data ) === range(0, sizeof( $data ) - 1)) { $output = array (); foreach ( $data as $value ) { $output [] = Json::encode( $value ); } return '[ ' . implode( ', ' , $output ) . ' ]' ; } case 'object' : $output = array (); foreach ( $data as $key => $value ) { $output [] = Json::encode( strval ( $key )) . ': ' . Json::encode( $value ); } return '{ ' . implode( ', ' , $output ) . ' }' ; default : return 'null' ; } } } static public function decode( $json , $assoc = FALSE) { if (function_exists( 'json_decode' )) { return json_decode( $json ); } else { $match = '/".*?(?<!\\\\)"/' ; $string = preg_replace( $match , '' , $json ); $string = preg_replace( '/[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/' , '' , $string ); if ( $string != '' ) { return NULL; } $s2m = array (); $m2s = array (); preg_match_all( $match , $json , $m ); foreach ( $m [0] as $s ) { $hash = '"' . md5( $s ) . '"' ; $s2m [ $s ] = $hash ; $m2s [ $hash ] = str_replace ( '$' , '\$' , $s ); } $json = strtr ( $json , $s2m ); $a = ( $assoc ) ? '' : '(object) ' ; $data = array ( ':' => '=>' , '[' => 'array(' , '{' => "{$a}array(" , ']' => ')' , '}' => ')' ); $json = strtr ( $json , $data ); $json = preg_replace( '~([\s\(,>])(-?)0~' , '$1$2' , $json ); $json = strtr ( $json , $m2s ); $function = @create_function( '' , "return {$json};" ); $return = ( $function ) ? $function () : NULL; unset( $s2m ); unset( $m2s ); unset( $function ); return $return ; } } } |