How to return json data in php (code)

不言
Release: 2023-04-03 15:24:01
Original
27479 people have browsed it

The content of this article is about how PHP returns json data (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. The return format is:

[
    {"id":"1","address":"IANA"},
    {"id":"2","address":"美国"}
]
Copy after login

php code:

<?php    
header(&#39;Content-Type:application/json&#39;);  //此声明非常重要
    try {        
    $conn = new PDO("mysql:host=localhost;dbname=orig", &#39;admin&#39;, &#39;admin&#39;);        
    $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防止中文乱码
    ?>
Copy after login

2. The return format is:

{
    "total":2,
    "rows":[
        {"id":"1","address":"IANA"},
        {"id":"2","address":"美国"}
    ]}
Copy after login

php code:

<?php
    header(&#39;Content-Type:application/json&#39;);    
    try {        
    $conn = new PDO("mysql:host=localhost;dbname=orig", &#39;admin&#39;, &#39;admin&#39;);        
    $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[&#39;total&#39;] = count($result);    
    $json[&#39;rows&#39;] = $result;    
    echo json_encode($json,JSON_UNESCAPED_UNICODE);
    ?>
Copy after login

Recommended related articles:

How to create a soft connection (code) in PHP

##Performance optimization tool in PHP: Detailed explanation of php generator

The above is the detailed content of How to return json data in php (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!