Zend本身提供了许多有用的工具来方便使用。比如这次提到的Zend_Json。本身就非常便利。该类处于这个目录下:
Zend/
Json/
Decoder.php
Encoder.php
Exception.php
Json.php
With Zend_Json, encoding PHP data structure into JSON formatted string is really easy. All you have to do is include Zend_Json
to your PHP script and call Zend_Json::encode()
with the variable you want to encode as parameter:
require_once 'Zend/Json.php'; $result = array('wine'=>3, 'sugar'=>4, 'lemon'=>22); echo Zend_Json::encode($result);
Reverse Operation: Decoding
Besides encoding, Zend_Json can also decode JSON formatted string. Provided a JSON formatted string, Zend_Json:decode()
will transform it into native PHP array:
require_once 'Zend/Json.php'; $result = Zend_Json::decode( '{"wine":3,"sugar":4,"lemon":22}'); print_r( $result);
Troubleshooting
Q: Why am I receiving the following error?
Parse error: parse error, unexpected T_ARRAY, expecting '&' or T_VARIABLE in [PROJECT_PATH]/Zend/Json/Encoder.php on line 402
A: Your PHP version is too low. Make sure you are using PHP 5.1.4 or later.