本篇文章给大家带来的内容是关于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); ?>
相关文章推荐:
Atas ialah kandungan terperinci php如何来实现返回json数据(代码). Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!