Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.



Get Started Now!

Convert Array to JSON in PHP

Laravel

Converting an array to JSON in PHP is straightforward, thanks to the built-in json_encode() function. Here’s a detailed tutorial with examples to guide you through the process.

Step 1: Understanding JSON and PHP Arrays

  • JSON (JavaScript Object Notation) is a lightweight data-interchange format that’s easy for humans to read and write, and easy for machines to parse and generate.
  • PHP Arrays are data structures that can hold multiple values, making them ideal for converting into JSON format.

Basic Syntax of json_encode()

json_encode(mixed $value, int $options = 0, int $depth = 512): string|false
  • $value: The array you want to convert.
  • $options: Optional flags to control the JSON output.
  • $depth: Maximum depth to traverse (default is 512).

Example 1: Simple PHP Array to JSON

PHP Array

// Define a simple associative array
$person = array(
    "name" => "John Doe",
    "age" => 30,
    "email" => "johndoe@example.com"
);

// Convert to JSON
$jsonData = json_encode($person);

// Display the JSON
echo $jsonData;

Output:

{"name":"John Doe","age":30,"email":"johndoe@example.com"}

Example 2: Multidimensional Array to JSON

PHP Multidimensional Array

// Define a multidimensional array
$people = array(
    array(
        "name" => "John Doe",
        "age" => 30,
        "email" => "johndoe@example.com"
    ),
    array(
        "name" => "Jane Smith",
        "age" => 25,
        "email" => "janesmith@example.com"
    )
);

// Convert to JSON
$jsonData = json_encode($people);

// Display the JSON
echo $jsonData;

Output:

[{"name":"John Doe","age":30,"email":"johndoe@example.com"},{"name":"Jane Smith","age":25,"email":"janesmith@example.com"}]

Example 3: Using JSON Options for Readability

Using the JSON_PRETTY_PRINT Option

// Convert with JSON_PRETTY_PRINT option
$jsonData = json_encode($people, JSON_PRETTY_PRINT);

// Display the formatted JSON
echo $jsonData;

Output:

[
    {
        "name": "John Doe",
        "age": 30,
        "email": "johndoe@example.com"
    },
    {
        "name": "Jane Smith",
        "age": 25,
        "email": "janesmith@example.com"
    }
]

Example 4: Handling Special Characters

If your array contains special characters, you can use the JSON_UNESCAPED_UNICODE option:

// Define an array with special characters
$data = array(
    "name" => "José López",
    "city" => "São Paulo",
    "country" => "España"
);

// Convert to JSON with special characters unescaped
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);

// Display the JSON
echo $jsonData;

Output:

{"name":"José López","city":"São Paulo","country":"España"}

Example 5: Error Handling in JSON Conversion

You can check if json_encode() encounters any errors during conversion using json_last_error() and json_last_error_msg():

// Define an array with invalid UTF-8 characters
$invalidData = array("name" => "Invalid \xB1 data");

// Attempt to convert to JSON
$jsonData = json_encode($invalidData);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON Encoding Error: " . json_last_error_msg();
} else {
    echo $jsonData;
}

Output:

JSON Encoding Error: Malformed UTF-8 characters, possibly incorrectly encoded

Summary of JSON Options

  • JSON_PRETTY_PRINT: Formats the JSON to be more human-readable.
  • JSON_UNESCAPED_UNICODE: Prevents escaping of Unicode characters.
  • JSON_UNESCAPED_SLASHES: Prevents escaping of / characters.
  • JSON_NUMERIC_CHECK: Converts numeric strings to numbers.

By following this tutorial, you should now be comfortable converting PHP arrays into JSON using the json_encode() function with various options for handling special cases.

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
1
0
Would love your thoughts, please comment.x
()
x