JSON一种轻量级的数据格式,由一位资深的软件工程师Douglas Crockford开发,全称为Javascript Object Notation。中文翻译为“JavaScript对象表示”,这个格式的数据可以很容易的被转换为javascript对象的格式,用于服务器端和客 户端的数据传递,用于解决xml的过多冗余标签造成数据传输量过大的问题。
PHP JSON类库是一个自动完成JSON编码和解码的php开源代码工具。
下载:http://www.eb163.com/code/json.rar
其中的TEST_JSON.php中包含了PHPUnit.php,是PEAR自带的单元测试工具,实际开发中可以不用。
PHP JSON类库示例代码:
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><span> ? </span></span></span></li> <li><span>//create a new instance of Services_JSON </span></li> <li class="alt"><span>require_once('JSON.php'); </span></li> <li> <span>$</span><span class="attribute">json</span><span> = </span><span class="attribute-value">new</span><span> Services_JSON(); </span> </li> <li class="alt"><span>// convert a complex value to JSON notation </span></li> <li> <span>$</span><span class="attribute">value</span><span> = </span><span class="attribute-value">array</span><span>('name'=</span><span class="tag">></span><span>'coollzh'<br>,'age'=</span><span class="tag">></span><span> 22,'data'=</span><span class="tag">></span><span>'foo'); </span> </li> <li class="alt"> <span>$</span><span class="attribute">output</span><span> = $json-</span><span class="tag">></span><span>encode($value); </span> </li> <li><span>print($output); </span></li> <li class="alt"> <span>//采用post方式发送数据: </span><span class="attribute">json</span><span>=<br>{"name":'coollzh',"age":2,"data":"foo"} </span> </li> <li><span>print($_REQUEST['json']); </span></li> <li class="alt"> <span>$</span><span class="attribute">value</span><span>= $json-</span><span class="tag">></span><span>decode(str_replace<br>('\','',$_REQUEST["json"])); </span> </li> <li><span>var_dump( $value); </span></li> <li class="alt"> <span>echo "</span><span class="tag"><span> </span><span class="tag-name">br</span><span class="tag">></span><span>".$value-</span><span class="tag">></span><span>data; </span></span> </li> <li> <span class="tag">?></span><span> </span> </li> </ol>
希望大家通过以上PHP JSON类库的代码示例,能初步了解它的具体含义。