AppDividend
Latest Code Tutorials

PHP json_encode() | How to Convert PHP Array to JSON

2

PHP json_encode() is an inbuilt function that converts a PHP value to JSON value. Objects in PHP can be converted into JSON by using the PHP function called json_encode(). The json_encode() function returns the string, if the function works.  Arrays in PHP will also be converted into JSON when using the PHP function json_encode(). You can find the example of covert PHP Array to JSON.

What is JSON

JSON stands for JavaScript Object Notation. It is data saved in the .json file and consists of a series of key/value pairs. JSON is used to transfer the data between the server and the browser. Here is a primary example of what might be in a .json string.

If you’re passing JSON data to a javascript program, make sure your program begins with:

<?php
    header('Content-Type: application/json');
?>

PHP json_encode Example

The syntax of json_encode() function is following.

json_encode(value, options)

The value parameter is required and of type mixed.

The options Bitmask comprising of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.

The json_encode() function returns a string, if the function works.

Let’s see the following example.

<?php

// app.php

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr)."\n";

The output is following.

Encode JSON Data In PHP Tutorial

Convert PHP Object to JSON 

PHP json_encode() method can convert PHP Object to JSON. So objects in PHP can easily convert into JSON using PHP json_encode() method.

<?php

// app.php

class App {
  
}
$app = new App();
$app->title = 'Harry Potter Game';
$app->price = 20;

$jsonData = json_encode($app);
echo $jsonData."\n";

So, we have defined one class App and then created an object and set the properties and convert the object to JSON and print that JSON output. The output is the following.

Convert PHP Object to JSON

Convert PHP String to JSON

PHP json_encode() function is useful to convert String to JSON object .

// app.php

$str = "hello AppDividend";
echo json_encode($str)."\n";

The output will be the same as the string.

You can use the json_encode() in any PHP Framework.

If the array keys in your PHP array are not consecutive numbers, json_encode() must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.

Use array_values() on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering.

PHP is a server-side programming language and should be used for operations that can only be performed by a server, like accessing a database.

How to convert PHP array to JSON

We can convert PHP array to json using the json_encode() function.

See the following code.

<?php

// app.php

$arr = array('Millie' => 'Eleven', 
            'Mike' => 'Finn', 
            'Gaten' => 'Dustin', 
            'Noah' => 'Will'); 
echo json_encode($arr)."\n";

See the output.

➜  pro php app.php
{"Millie":"Eleven","Mike":"Finn","Gaten":"Dustin","Noah":"Will"}
➜  pro

Convert Multidimensional PHP Array into JSON

Let’s see an example where we can encode the multidimensional array.

<?php

// app.php

$post_data = array(
  'item' => array(
    'item_type_id' => 1,
    'string_key' => 'AA',
    'string_value' => 'Hello',
    'string_extra' => 'App',
    'is_public' => 1,
   'is_public_for_contacts' => 0
  )
);

echo json_encode($post_data)."\n";

The output of the above code is following.

Convert Multidimensional PHP Array into JSON

Generally, you have to use json_encode() function when you need to send an AJAX request to the server because JSON data is useful to transfer between client and server. So converting PHP to JSON, Javascript to JSON is easy. That is why the JSON object contributes to a significant role in today’s web development.

The reverse process of json_encode is json_decode().

Decoding JSON data is as simple as encoding it. You can use a PHP json_decode() function to convert a JSON encoded string into the appropriate PHP data type.

Conclusion

JSON encode decode is one of the most frequently required operations. In this article, we have seen how to encode and decode JSON using PHP and seen two inbuilt functions to perform the various operations. Those are,

  1. json_encode()
  2. json_decode()

We have seen how to convert PHP array to json and PHP object to json using PHP json_encode() function.

Finally, PHP json_encode Example is over.

See also

PHP array_key_exists()

PHP array_fill_keys()

PHP array_column()

PHP Object to Associative array

PHP ksort()

2 Comments
  1. santosh says

    Nice Explanation, I was doubt about JSON but now clear.

  2. Michael Hochleitner says

    Thank you Krunal!

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.