php自学系列(2)xml操作类

时间:14-08-11 栏目:Php 作者:zongyan86 评论:0 点击: 2,426 次

xml操作类

   /**
    * 按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'?>\n";
        $xml .= "<root>\n";

        $xml .= self::xmlToEncode($result);

        $xml .= "</root>";
        echo $xml;
    }

    public static function xmlToEncode($data) {

        $xml = $attribute= "";
        foreach($data as $key => $value) {
            if(is_numeric($key)) {
                $attribute = " id='{$key}'";
                $key = "item";
            }
            $xml .= "<{$key}{$attribute}>";
            $xml .= is_array($value) ? self::xmlToEncode($value) : $value;    // 这里使用了递归
            $xml .= "</{$key}>\n";
        }
        return $xml;
    }


声明: 本文由( zongyan86 )原创编译,转载请保留链接: php自学系列(2)xml操作类

关注我们