您的位置:首页 > 编程语言 > PHP开发

php将从数据库查询到的数据转化为json格式,并写入json文件中

2017-12-07 23:39 1056 查看
1.主要是对数据进行编码

$str=json_encode($jarr);//将数组进行json编码

2.其次是写入json文件中
$file = fopen("../../code/myCode/menu/dessert.json","w");
echo fwrite($file,$str);

完整代码如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
</head>
<body>
<?php

header("Content-type:text/html;charset=utf8");//字符编码设置
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "userinfo";

// 创建连接
$con =mysqli_connect($servername, $username, $password, $dbname);

//$charset=mysqli_character_set_name($con); //返回数据库默认字符集的编码utf8 gb2312_chinese_ci
//echo "默认字符集为: " . $charset;

$sql = "SELECT * FROM dessert";

$result = mysqli_query($con,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}

$jarr = array();
while ($rows=mysqli_fetch_array($result,MYSQL_ASSOC)){
$count=count($rows);//不能在循环语句中,由于每次删除 row数组长度都减小
for($i=0;$i<$count;$i++){
unset($rows[$i]);//删除冗余数据
}
array_push($jarr,$rows);
}
print_r($jarr);//查看数组
echo "<br/>";

echo '<hr>';

echo '编码后的json字符串:';
echo $str=json_encode($jarr);//将数组进行json编码

$file = fopen("../../code/myCode/menu/dessert.json","w");// http://127.0.0.1:8088/TomcatTest/phpbin/index.php echo fwrite($file,$str);
fclose($file);
mysqli_close($con);
?>
</body>
</html>

注意:对数据进行json编码后,中文在网页上显示为unicode编码,如\u63d0。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: