我有这个PHP代码从数据库提供数据,然后转换为json文本文件,我的数据库名称是gengroup_testwebapp,我的json文件是jsonparsetutorial.txt:
<?php
// open a connection to mysql
$conn = mysqli_connect("localhost","gengroup_ali","GenGroup$2015","gengroup_testwebapp")
or die("Error is : ".mysqli_error($conn));
//fetching data to php
$sql = "select * from country_info";
$result = mysqli_query($conn , $sql) or die("Error is : ". mysqli_error($conn));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
// convert php array to json String and \n
//write to json file
$fp = fopen('jsonparsetutorial.txt', 'worldpopulation');
fwrite($fp, json_encode($emparray));
fclose($fp); ?>
我想将此代码转换为json数组文件。如何将其数据转换为json文件,如下所示:
{ "worldpopulation":
[
{
"rank":1,"country":"China",
"population":"1,354,040,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/china.png"
},
{
"rank":2,"country":"India",
"population":"1,210,193,422",
"flag":"http://www.gengroup.ir/testwebapp/flag/india.png"
},
{
"rank":3,"country":"United States",
"population":"315,761,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/unitedstates.png"
},
{
"rank":4,"country":"Indonesia",
"population":"237,641,326",
"flag":"http://www.gengroup.ir/testwebapp/flag/indonesia.png"
},
{
"rank":5,"country":"Brazil",
"population":"193,946,886",
"flag":"http://www.gengroup.ir/testwebapp/flag/brazil.png"
},
{
"rank":6,"country":"Pakistan",
"population":"182,912,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/pakistan.png"
},
{
"rank":7,"country":"Nigeria",
"population":"170,901,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/nigeria.png"
},
{
"rank":8,"country":"Bangladesh",
"population":"152,518,015",
"flag":"http://www.gengroup.ir/testwebapp/flag/bangladesh.png"
},
{
"rank":9,"country":"Russia",
"population":"143,369,806",
"flag":"http://www.gengroup.ir/testwebapp/flag/russia.png"
},
{
"rank":10,"country":"Japan",
"population":"127,360,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/japan.png"
}
] }
答案 0 :(得分:1)
只需这样做。
#dblock
别忘了提及像 w 这样的开放模式进行写作。