How to convert php array to json object with example?

Today, We want to share with you php convert array to json.In this post we will show you php string to json, hear for how to get data from json array in php? we will give you demo and example for implement.In this post, we will learn about json to array php with an example.

Convert PHP Object To JSON | PHP Array To JSON

Example 1:

<?php
  
  $websiteList = ['4cgandhi', 'Pakainfo', 'w3school', '.tamilrokers', 'Infinityknow'];
  
  $websiteListJSON = json_encode($websiteList);
  
  echo $websiteListJSON;
  
?>

Results
["4cgandhi","Pakainfo","w3school",".tamilrokers","Infinityknow"]

Example 2:

<?php
  
  $websiteList = ['4cgandhi', 'Pakainfo', 'w3school', '.tamilrokers', 'Infinityknow'];
   
  $websiteListJSONObject = json_encode($websiteList, JSON_FORCE_OBJECT);
   
  echo $websiteListJSONObject;
    
?>

Results
{"0":"4cgandhi","1":"Pakainfo","2":"w3school","3":".tamilrokers","4":"Infinityknow"}

Example 3:

<?php
  
  $details = ['name'=>'Pankil', 'website'=>'infinityknow.com'];
  
  $jsonDetails = json_encode($details);
  
  echo $jsonDetails;
     
?>

Results

{"name":"Pankil","website":"infinityknow.com"}

Convert JSON To PHP Array

$json = json_encode($player);

// print the array
print_r(json_decode($json));

Output

(
    [name] => Pankil
    [email] => [email protected]
)

Convert PHP Object to JSON

<?php
class Product {
  // Properties
  public $name;
  public $color;

  // Methods
  function set_name($name) {
    $this->name = $name;
  }

  function set_color($color){
      $this->color = $color;
  }

  function get_name() {
    return $this->name;
  }

  function get_color(){
      return $this->color;
  }
}

$iphone = new Product();
$iphone->set_name('Iphone');
$iphone->set_color('White');

echo print_r($iphone);

Product Object
(
    [name] => Iphone
    [color] => White
)

Free Live Chat for Any Issue

echo json_encode($iphone);

Results

{"name":"Iphone","color":"White"}

Convert PHP Array to JSON

First create an array.

$player = array('name' => 'Pankil', 'email' => '[email protected]');

 $player = array('name' => 'Pankil', 'email' => '[email protected]');

 print_r($player);

 echo "---------------- \n";

 echo json_encode($player);

Results:

Array
(
    [name] => Pankil
    [email] => [email protected]
)
---------------- 
{"name":"Pankil","email":"[email protected]"}

Download

I hope you get an idea about php json_encode object.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.