如何使用php来实现给前端返回json数据

如何使用php来实现给前端返回json数据

    • 数据库中查询返回json
    • 返回多个字段的json格式

数据库中查询返回json

[
    {"id":"1","address":"China"},
    {"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:
"
. $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防止中文乱码 ?>

返回多个字段的json格式

{

    "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:
"
. $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); ?>

你可能感兴趣的:(Php)