首页  >  文章  >  后端开发  >  封装通信接口数据的方法-xml

封装通信接口数据的方法-xml

WBOY
WBOY原创
2016-07-29 09:03:16936浏览

php生成XML数据

1)组装字符串

2)使用系统类

- DomDocument

- XMLWriter

- SimpleXML

这里以第一种方法举例:

<?php class Response
{

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

        $result = array(
            &#39;code&#39; => $code,
            'message' => $message,
            'date' => $data
        );

        echo json_encode($result);
        exit;
    }

    public static function xml(){
        header("content-type:text/xml");
        $xml = "<?xml version=&#39;1.0&#39; encoding=&#39;UTF-8&#39;?>\n";
        $xml .= "<root>\n";
        $xml .="<code>200</code>\n";
        $xml .="<message>数据返回成功</message>\n";
        $xml .="<data>\n";
        $xml .="<id>1</id>\n";
        $xml .="<name>ceshi</name>\n";
        $xml .="</data>\n";
        $xml .= "</root>\n";

        echo $xml;
    }

    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=&#39;1.0&#39; encoding=&#39;UTF-8&#39;?>";
        $xml .="<root>\n";
        $xml .= self::xmlToEncode($result);
        echo $xml .="</root>";
    }

    public static function xmlToEncode($data){
        $xml = $attr = '';
        foreach($data as $key => $value){
            if(is_numeric($key)){
                $attr = " id='{$key}'";
                $key = 'item';
            }
            $xml .= "";
            $xml .= is_array($value)?self::xmlToEncode($value):$value;  //递归,如果value是数组,递归输出节点。
            $xml .= "{$key}>\n";
        }
        return $xml;
    }
}

$arr = array(
    'id' => 1,
    'name' => 'xxx',
    'type' => array(4,5,6),
    'test' => array(1,25,345=>array(123,'zifuchuan'))
);
//40> <item id="'0'">4</item>

//Response::json(200,'数据返回成功',$arr);
//Response::xml();
Response::xmlEncode(200,'success',$arr);

以上就介绍了封装通信接口数据的方法-xml,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn