Home > Backend Development > PHP Tutorial > About the method of encapsulating data in xml

About the method of encapsulating data in xml

不言
Release: 2023-04-02 11:44:02
Original
2502 people have browsed it

This article mainly introduces the method of encapsulating data in xml, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

  1. xml encapsulation Data method

##2.demo

<?php
xml方式封装数据方法
/**
 * [xmlEncode description]
 * @param  [type] $code    [description]
 * @param  [type] $message [description]
 * @param  array  $data    [description]
 * @return [type]          [description]
 */
public static function xmlEncode($code,$message,$data= array()){
    if(!is_numeric($code)){
        return;
    }    
    $result = array(
        &#39;code&#39;=>$code,
        &#39;message&#39;=>$message,
        &#39;data&#39;=>$data,
        );
    header("Content-Type:text/html");
    $xml ="<?xml version=&#39;1.0&#39; encoding=&#39;UTF-8&#39;>";
    $xml .="<root>";
    $xml .=self::xmlToEncode($result);
    $xml .="</root>";

 echo $xml;
}


public static function xmlToEncode($data){
    $xml = $attr "";
    foreach ($data as $key => $value) {
        //xml的节点不能为数字,如果传默认数组需要处理下标值
        if(is_numeric($key)){
            $attr = "id=&#39;{$key}&#39;";
            $key = "item";
        }
        $xml .="<{$key}>";    
        $xml .=is_array($value)?self::xmlToEncode($value):$value;    
        $xml .="</{$key}>";    
    }
    return $xml;

}
$data = array(
    &#39;id&#39;=>1,
    &#39;name&#39;=>&#39;xinlang&#39;,
    &#39;type&#39;=>array(),
    );
Response::xmlEncode(200,&#39;success&#39;,$data);


//注意 xml的节点不能为数字,如果传默认数组需要处理下标值
<item id="0"></item>
Copy after login

Running result:

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to configure independent subdomain names in the yii backend

The above is the detailed content of About the method of encapsulating data in xml. 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