本站重新定位为
分享技术和经验的个人博客

php读取MySQL数据并返回json数据

<?php
//设置编码格式
header("Content-type:application/json;charset=utf-8"); 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$dbname = "test"; 
class User {
public $id;
public $name;
public $age;
public $sex;
}
//汉字转码
function decodeUnicode($str){
return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
create_function(
'$matches',
'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
),
$str);
}
$data = array();
// 创建连接 
$con =mysqli_connect($servername, $username, $password, $dbname); 
// 检测连接 
$sql = "SELECT * FROM `user` WHERE 1"; 
$result = mysqli_query($con,$sql); 
if($result){
while ($row=mysqli_fetch_array($result,MYSQL_ASSOC)){ 
$user = new User();
$user->id = $row["id"];
$user->name = $row["name"];
$user->age = $row["age"];
$user->sex = $row["sex"];
$data[]=$user;
}
//打印编码后的json字符串
$json = json_encode($data);
echo decodeUnicode($json);
}else{
echo "查询失败";
}
mysqli_close($con);
?>
赞(0)
这篇文章为天际博客(天朝世纪)原创,转载请注明。天际部落 » php读取MySQL数据并返回json数据

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址