I have an online PHP/mySQL database from which I need an android app to be populated with data. How do I create a JSON file from the PHP/mySQL database?
4 Answers
just select what you need from your DB, put it in $array
and use
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
for example:
$json = json_encode($array)
and then put it in the file with:
int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
example:
file_put_contents('file.json', $json)
2 Comments
user3742590
Thanks a lot, I really understood that and I think that could help out. Could you please tell me what the problem in this code is?
user3742590
try { $con = mysql_connect("localhost","muhit","", "canteendb"); mysql_select_db("canteendb", $con); $returnArray = array(); $sql = "SELECT itemName, pricePerUnit, unit, restaurantID, category FROM Item WHERE 1 "; $query = mysql_query($sql); while($rs = mysql_fetch_array($query, MYSQL_ASSOC)) { $returnArray[] = $rs; } $fp = fopen('C:/Users/Ishtiaq/Downloads/Compressed/Codes/json/file4.json', 'w+'); file_put_contents('C:/Users/Ishtiaq/Downloads/Compressed/Codes/json/file4.json', $json) fwrite($fp, json_encode($returnArray)); fclose($fp); mysql_close($con); }