Getting data from MySQL into JSON using PHP

Home > Json Tutorial > Getting data from MySQL into JSON using PHP

Best PHP Live Project Based Winter Training in Noida for more details click here



PHP Script for fetching data from mysql and store in JSON file

<?php
$host="localhost";
$user="root";
$pass="";
$db="demo";

//connect with database demo
$connect= new mysqli($host,$user,$pass,$db) or die("ERROR:could not connect to the database!!!");

//select all data from json table
$query="select * from json ";
$result=$connect->query($query);

//fetech all data from json table in associative array format and store in $result variable
$array=$result->fetch_assoc();

//Now encode PHP array in JSON string 
$json=json_encode($array,true);

//test the json string
var_dump($json);

//create file if not exists
$fo=fopen("myjson.json","w");

//write the json string in file
$fr=fwrite($fo,$json);

?>