PHP json_encode() Function

P
PHP json_decode() Function
PHP json_last_error() Function

In this article, you will learn how to encode a value to JSON format. The PHP method JSON_ENCODE() convert the given value to JSON format. The given value turns into a JSON object. JSON_ENCODE() function can encode both indexed as well as associative arrays.

What is the syntax of the JSON_ENCODE() function in php?

json_encode(value, options, depth)
ParameterDescription
valueRequired. Specifies the value to be encoded
optionsOptional. Specifies a bitmask (JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR)
depthOptional. Specifies the maximum depth
PHP JSON_ENCODE() method

examples of the JSON_ENCODE() function

Example 1. In this example, we encode an associative array into a JSON object.

<?php
$age = array("Peter"=>35, "Ben"=>37, "Joe"=>43);
echo json_encode($age);
?>

Example 2. In this example, we encode an indexed array into a JSON object.

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo json_encode($cars);
?>
PHP json_decode() Function
PHP json_last_error() Function

Add comment

Tutor Network

Share this

Learn PHP from A to Z