Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Reading and writing JSON in PHP


PHP is a popular server-side scripting environment easily integrated with the Apache and Microsoft IIS web servers. It has native support for simple JSON encoding and decoding.

How to do it...

PHP provides two functions, json_encode and json_decode, to encode and decode JSON respectively.

You can pass primitive types or user-defined classes to json_encode and it returns a string containing the JSON representing the object. For example:

$result = array(
"call" =>"KF6GPE",
"type" =>"l",
"time" =>"1399371514",
"lasttime" =>"1418597513",
"lat" =>37.17667,
"lng" =>-122.14650,
"result" =>"ok");
$json = json_encode($result);

This creates a string $json containing the JSON representation of our associative array.

The json_encode function takes an optional second argument, which lets you specify arguments to the encoder. The arguments are flags, so you combine them with the binary or | operator. You can pass a combination of the following flags:

  • JSON_FORCE_OBJECT...