<?php
$hostname = "192.168.136.129";
$username = "root";
$password = "1213800";
$database = "webData";
$con = mysqli_connect($hostname, $username, $password, $database);
if (!$con)
{
    die('Could not connect: ' . mysqli_error($con));
}
// 设置编码，防止中文乱码
mysqli_set_charset($con, "utf8");

$sql="select * from Tips order by rand() limit 5";

$result = mysqli_query($con,$sql);

$tips = array();

while($tip = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
    $tips[] = $tip;
}

class Response {
    public static function xml($code, $message = '', $data = []){

        # 判断参数有效性及错误处理
        // code...

        # 结果(最终数组)
        $xmlResult = [
            "code" => $code,
            "message" => $message,
            "data" => $data
        ];

        # 更改头部(为了更清晰的展示XML节点)
        header('Content-type: text/xml');//xml

        # 生成XML(字符串拼接方式)
        $xml = '<?xml version="1.0" encoding="UTF-8"?>';//xml head
        $xml .= '<root>';//拼接根节点(开始)

        $xml .= self::toXML($xmlResult);//调用处理函数

        $xml .= '</root>';//拼接根节点(结束)
        echo $xml;
    }

    # 解析结果数组转为对应的xml节点
    public static function toXML($data){//参数为data(result)

        # 临时存储xml数据
        $xml = $id = '';

        # 遍历并拼接字符串
        foreach($data as $key => $value){

            # 如果key是数字(即非关联数组 => [hello,2,true] )
            # 以 <item id='?'></item> 展示,id为key
            if(is_numeric($key)){//如果是数字
                $id = "id='{$key}'";//将key作为id属性
                $key = 'item ';//将item作为节点名
            }

            $xml .= "<{$key}{$id}>";//开始节点

            # 如果是数组则递归(否则直接返回value值)
            $xml .= is_array($value) ? self::toXML($value) : $value;

            $xml .= "</{$key}>";//结束节点
        }

        return $xml;
    }
}

# 调用
Response::xml(200, '返回成功', $tips);
mysqli_free_result($result);
mysqli_close($con);

