0
0
PhpHow-ToBeginner · 3 min read

How to Parse JSON in PHP: Simple Guide with Examples

To parse JSON in PHP, use the json_decode() function which converts a JSON string into a PHP variable. You can get an object or an associative array by setting the second parameter accordingly.
📐

Syntax

The json_decode() function takes a JSON string and converts it into a PHP variable. It has two main parameters:

  • string $json: The JSON string to parse.
  • bool $assoc (optional): When true, returns an associative array; when false or omitted, returns an object.

Example syntax:

json_decode(string $json, bool $assoc = false)
php
json_decode(string $json, bool $assoc = false);
💻

Example

This example shows how to parse a JSON string into a PHP object and an associative array, then access their values.

php
<?php
$jsonString = '{"name":"Alice","age":30,"city":"Paris"}';

// Parse as object (default)
$personObject = json_decode($jsonString);
echo "Name (object): " . $personObject->name . "\n";

// Parse as associative array
$personArray = json_decode($jsonString, true);
echo "Name (array): " . $personArray['name'] . "\n";
?>
Output
Name (object): Alice Name (array): Alice
⚠️

Common Pitfalls

Common mistakes when parsing JSON in PHP include:

  • Not checking if json_decode() returned null, which means parsing failed.
  • Forgetting to set the second parameter to true if you want an associative array.
  • Passing invalid JSON strings, which causes errors.

Always validate JSON and check for errors using json_last_error().

php
<?php
$jsonString = '{"name":"Alice","age":30}'; // Valid JSON (keys must be in double quotes)

$result = json_decode($jsonString);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON Error: " . json_last_error_msg() . "\n";
} else {
    echo "Parsed successfully.";
}
?>
Output
Parsed successfully.
📊

Quick Reference

Here is a quick summary of useful functions and options for JSON parsing in PHP:

Function/OptionDescription
json_decode($json, $assoc = false)Parse JSON string to PHP object or array
json_last_error()Returns error code from last JSON operation
json_last_error_msg()Returns readable error message
Second parameter $assocSet to true for associative array, false for object

Key Takeaways

Use json_decode() to convert JSON strings into PHP variables.
Set the second parameter of json_decode() to true to get an associative array.
Always check json_last_error() after decoding to catch errors.
JSON keys and string values must be enclosed in double quotes.
Invalid JSON will cause json_decode() to return null.