如何使用 php 写一个接口,然后将数据以 json 文件格式调用。
<?php
header('Content-Type:application/json; charset=utf-8');
header("Access-Control-Allow-Origin:*");
$servername = "localhost";
$username = "数据库账号";
$password = "数据库密码";
$dbname = "数据库名称";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "select slug,title,created,text from typecho_contents";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
$data[]=$row;
}
$json = json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);//把数据转换为JSON数据.
exit($json) ;
} else {
echo "未查询到结果!";
}
$conn->close();
?>
根据某个条件排序,将32行的sql语句改为下面的,意为根据 created
进行排序。
$sql = "select slug,title,created,text from typecho_contents order by created desc";