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.

<?php
// the array
$arrPerson= array(
	'name'=>'Michael',
	'city'=>'Munich',
	'age'=>28,
	'hobbies'=>array('surfing','swimming','chess')
);
 
?>

This array has the following structure:

array(4) {
  ["name"]=>
  string(7) "Michael"
  ["city"]=>
  string(6) "Munich"
  ["age"]=>
  int(28)
  ["hobbies"]=>
  array(3) {
    [0]=>
    string(7) "surfing"
    [1]=>
    string(8) "swimming"
    [2]=>
    string(5) "chess"
  }
}

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

<?php
// 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:

{"name":"Michael","city":"Munich","age":28,"hobbies":["surfing","swimming","chess"]}

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: https://www.php.net/manual/de/function.json-encode.php

(Visited 597 times, 1 visits today)

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

Leave a Comment