PHP生成xml数据-XML方式封装接口数据方法

//实例:
 //test2.php
 class Response {  

/**
     *PHP生成XML数据
     *1)组装字符串
     *2)使用系统类
     *    . DomDocument
     *    . XMLWriter
     *    . SimpleXML
     * 
     */

    //1)组装字符串生成XML数据
    public static function xml(){
        header("Content-Type:text/xml");
        $xml = "<?xml version='1.0' encoding='UTF-8'?>";
        $xml .= "<root>";
        $xml .= "<code>200</code>";
        $xml .= "<message>数据返回成功</message>";
        $xml .= "<data>";
        $xml .= "<id>1</id>";
        $xml .= "<name>小明</name>";
        $xml .= "</data>";
        $xml .="</root>";

        echo $xml;
    }
    //XML方式封装接口数据方法
    /**
     *
     * 封装方法
     * xmlEncode($code, $message = "", $data = array())
     * data数据分析
     * 1.array('index' => 'api');
     * 2.array(1,7,89);
     */
    

    /**
     * 按xml方式输出数据    
     * @param  integer $code   状态码    
     * @param  string $message 提示信息
     * @param  array  $data    数据
     * @return string          
     */
    public static function xmlEncode($code, $message = '', $data = array()){
        if (!is_numeric($code)) {
            return '';
        }

        $result = array(
            'code' => $code,
            'message' => $message,
            'data' => $data,
        );

        header("Content-Type:text/xml");
        $xml = "<?xml version='1.0' encoding='UTF-8'?>";
        $xml .= "<root>";
        $xml .= self::xmlToEncode($result);
        $xml .="</root>";
        echo $xml;
    }

    public static function xmlToEncode($data){
        
        $xml = $attr = "";
        foreach($data as $key => $value){
            if (is_numeric($key)) {    
                $attr = " id='{$key}'";
                $key = "item";
            }
            $xml .= "<{$key}{$attr}>";
            $xml .= is_array($value) ? self::xmlToEncode($value) : $value;
            $xml .= "</{$key}>";
        }
        return $xml;
    }
    
}
<?php
//test1.php
require('./models/test2.php');//引入test2.php

$data = array(
    'id' => 1,
    'name' => 'xiaojie',
    'test' => array(1,55,99,66),
);
//$test = new Response();//实例化test2.php文件中Response类
//$test->json(200,'数据返回成功',$data);

//$test->xml();

Response::xmlEncode(200,'数据返回成功',$data);
//浏览器执行test1.php文件返回结果

<root>
<code>200</code>
<message>数据返回成功</message>
<data>
<id>1</id>
<name>xiaojie</name>
<test>
<item id="0">1</item>
<item id="1">55</item>
<item id="2">99</item>
<item id="3">66</item>
</test>
</data>
</root>

 

posted @ 2017-12-04 13:44  enjie  阅读(483)  评论(0编辑  收藏  举报