本篇文章给大家带来的内容是关于php如何来实现返回json数据(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
一、返回格式为:
[
{"id":"1","address":"IANA"},
{"id":"2","address":"美国"}
]php代码:
<?php
header('Content-Type:application/json'); //此声明非常重要
try {
$conn = new PDO("mysql:host=localhost;dbname=orig", 'admin', 'admin');
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET NAMES utf8"); //设置编码
} catch(PDOException $e) {
echo "conn_error:<br/>" . $e -> getMessage();
} $sql = "select id,address from ip_segments limit 2;";
$result = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result,JSON_UNESCAPED_UNICODE); //JSON_UNESCAPED_UNICODE防止中文乱码
?>二、返回格式为:
{
"total":2,
"rows":[
{"id":"1","address":"IANA"},
{"id":"2","address":"美国"}
]}php代码:
<?php
header('Content-Type:application/json');
try {
$conn = new PDO("mysql:host=localhost;dbname=orig", 'admin', 'admin');
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET NAMES utf8");
} catch(PDOException $e) {
echo "conn_error:<br/>" . $e -> getMessage();
}
$sql = "select id,address from ip_segments limit 2;";
$result = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$json['total'] = count($result);
$json['rows'] = $result;
echo json_encode($json,JSON_UNESCAPED_UNICODE);
?>相关文章推荐:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
立即学习“PHP免费学习笔记(深入)”;
以上就是php如何来实现返回json数据(代码)的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号