Convert Array to JSON in PHP

PHP convert array data to json data; Through this tutorial, i am going to show you how to convert array to json data in PHP.

How to Convert Array to JSON in PHP

PHP json_encode() function is used to convert PHP array or object into JSON.

Using the php json_encode() function, i will take following example to convert array data to json object data in PHP; as follows:

  • Example 1 – PHP Convert Array Data to JSON Data
  • Example 2 – Convert Object to JSON in PHP
  • Example 3 – Convert String to JSON in PHP
  • Example 4- PHP Convert Multidimensional Array into JSON

Example 1 – PHP Convert Array Data to JSON Data

Let’s take first example to convert array data to json data using php json_encode(); is as follows:

<?php

$arr = array('name' => 'test', 'email' => '[email protected]', 'mobile' => '88888xxxx', 'age' => 25);
echo json_encode($arr)."\n";

?>

The output of the above given code; is as follows:

{"name":"test","email":"[email protected]","mobile":"88888xxxx","age":25}

Example 2 – Convert Object to JSON in PHP

Let’s take second example to convert object data to json data using php json_encode(); is as follows:

<?php

class Color {
  
}

$color = new Color();
$color->title = 'Block';
$color->code = 'FFF';

$json = json_encode($color);
echo $json."\n"; 

?>

The output of the above given code; is as follows:

{"title":"Block","code":"FFF"}

Example 3 – Convert String to JSON in PHP

Let’s take third example to convert object data to json data using php json_encode(); is as follows:

<?php

$string = "hello php dev";
echo json_encode($string)."\n";

?>

The output of the above given code; is as follows:

hello php dev

Example 4- PHP Convert Multidimensional Array into JSON

Let’s take fourth example to convert object data to json data using php json_encode(); is as follows:

<?php

$data = array(
  'product' => array(
    'product_id' => 1,
    'product_color' => 'Black',
    'product_name' => 'Laptap',
    'brand_name' => 'DELL',
  )
);

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

?>

The output of the above given code; is as follows:

{"product":{"product_id":1,"product_color":"Black","product_name":"Laptap","brand_name":"DELL"}} 

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.