0

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 4

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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); }
0

Create an php file and access the database. With

json_encode($array)

you can produce a json representative from your array. Depending on your planned App you can just echo the json or use some kind of soap webservice

Comments

0

Just use a php command to encode anything in json. Here is the php command which lets you to encode anything in json.

json_encode($text)

After encoding just put file_get_contents() function in php to put it in a .json file

Comments

0

In order to have JSON format of your data in the database:

  1. Fetch the data from the database using PHP and store them as an array called $data
  2. Convert the the array $data to JSON, use echo json_encode($data);to have them printed in JSON format

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.