Encoding PHP Data Structure
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);Running above script will produce a JSON representation of
$result
:{"wine":3,"sugar":4,"lemon":22}
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);Above code will produce the following output:
Array ( [wine] => 3 [sugar] => 4 [lemon] => 22 )As you can see, the result returned by
Zend_Json::decode()
in this example is an array and it holds the same data as the one in previous example.
No comments:
Post a Comment