Parsing a JSON String in PHP

To parse a JSON string to a PHP object or array, you can use the json_decode($json) function. The json_decode() function recursively converts the passed JSON string into the corresponding PHP objects. You can control the parsing flow by passing a set of bitmasks to the JSON decoder function. If the JSON cannot be parsed or the nested JSON data has a depth greater than the recursion limit, the json_decode() returns NULL. The PHP JSON parser only works with UTF-8 encoded strings. To encode PHP objects to JSON string, you can use json_encode($value) function. In this PHP JSON Parse example, we use the json_decode() function to decode JSON strings into PHP objects. Click Execute to run the PHP Parse JSON Example online and see the result.
Parsing a JSON String in PHP Execute
<?php
$json = '["Orange", "Apple", "Lemon"]';

print_r (json_decode($json));
?>
Updated: Viewed: 9303 times

What is PHP?

PHP is a general-purpose server-side programming language used for web development that can be embedded into HTML code. PHP combines with web development technologies such as HTML, CSS, JavaScript, and SQL. PHP is known for its flexibility and big developer community. PHP is also a cross-platform programming language, which allows it to work on various operating systems such as Linux, Unix, Windows, and macOS.

What is JSON?

JavaScript Object Notation (JSON) is a standard text format for storing and transmitting data over a network. JSON comes from JavaScript and has a syntax similar to JavaScript but can be used separately from it. JSON is used for client/server communication in mobile and web applications written in many programming languages, including JavaScript, Python, Java, C++, C#, Go, PHP, and others.

How to decode JSON data in PHP?

To decode JSON string in PHP, you can use the json_decode() function to convert the JSON string to the appropriate PHP data type. The example below shows how to parse or decode a JSON string to a PHP object:

PHP Decode JSON Example
<?php
$json = '{"Leo":25,"Alice":37,"Tim":43}';

print_r (json_decode($json));
?>

#output: stdClass Object
#(
#    [Leo] => 25
#    [Alice] => 37
#    [Tim] => 43
#)

How to encode a PHP object to JSON string?

To encode PHP objects into JSON strings, you can use the json_encode() function. A PHP object can be of any PHP data type except for a resource such as a database or a file descriptor. The example below shows how to encode a PHP associative array into a JSON string:

PHP Encode JSON Example
<?php
$json = array(
  'Leo' => 35,
  'Alice' => 37, 
  'Dora' => 43
);

echo json_encode($json);
?>

#output: {"Leo":35,"Alice":37,"Dora":43}

See also