jeudi 25 juin 2020

How to modify this PHP code to send data to json file on server as shown below json format

 <?php  
 $message = '';  
 $error = '';  
 if(isset($_POST["submit"]))  
 {  
      if(empty($_POST["title"]))  
      {  
           $error = "<label class='text-danger'>Enter  details</label>";  
      }  
      else if(empty($_POST["image"]))  
      {  
           $error = "<label class='text-danger'>Enter Written By</label>";  
      }  
      else  
      {  
           if(file_exists('myfile.json'))  
           {  
                $current_data = file_get_contents('myfile.json');  
                $array_data = json_decode($current_data, true);  
                $extra = array(  
                     'title'  =>     $_POST['title'],  
                     'image'  =>     $_POST["image"],  
                     'link'   =>     $_POST['link'],  
                     'info'   =>     $_POST['info'],  
                );  
                $array_data[] = $extra;  
                $final_data = json_encode($array_data);  
                if(file_put_contents('myfile.json', $final_data))  
                {  
                     $message = "<label class='text-success'>Added Successfully</p>";  
                }  
           }  
           else  
           {  
                $error = 'JSON File not exits';  
           }  
      }  
 }  
 ?>

Above is my PHP code that i have for sending data to json present on server.

{
"Apple": [
  {
    "title": "iphone5",
    "image": "lllllll",
    "link": "llllll",
    "info":"llllll"
  },
  
  {
    "title": "iphone6",
    "image": "lllllll",
    "link": "llllll",
    "info":"llllll"
  }
]
}

Above is my json file format that i want to have after submitting data using PHP, it should not override myfile or something like that, i want it to be add more childs in array using PHP

[
  {
    "title": "Aiphone5",
    "image": "lllllll",
    "link": "llllll",
    "info":"llllll"
  },
  
  {
    "title": "Aiphone6",
    "image": "lllllll",
    "link": "llllll",
    "info":"llllll"
  }
]

If i run as shown above php code the o/p of json is as above




Aucun commentaire:

Enregistrer un commentaire