PHP: Convert An Array To JSON

Sometimes, when programming in PHP, you’ll need to convert an array to JSON. This enables you e.g. to retrieve data serverside through PHP and pass it to the client, which then can process this data with javascript. There are different ways to do that, e.g. via AJAX.
In this article I’ll show you, how easy it is to convert a PHP array into a JSON String.

I use the following PHP array. Please note, that all data must be utf-8 encoded.

// the array
$arrPerson= array(

This array has the following structure:

array(4) {
  string(7) "Michael"
  string(6) "Munich"
  array(3) {
    string(7) "surfing"
    string(8) "swimming"
    string(5) "chess"

Now, encode the array into a JSON string. This is easyly done in PHP with the json_encode() function.

// Now encode the array to a json string
$result = json_encode($arrPerson);

In this example, I am using only one parameter. This parameter contains the array. By using json_encode(), you can also pass two additional optional parameters. The second parameter can contain JSON constants as options. The third parameter can pass a depth limit to walk through the array structure.

Now we have a variable $result, which holds the following JSON string:


That’s it. By the way, you can also convert an object to JSON.
More information about the json_encode() function can be found here:

(Visited 560 times, 1 visits today)

1 thought on “PHP: Convert An Array To JSON”

Leave a Comment