>  기사  >  백엔드 개발  >  PHP는 json 및 xml 유형 인터페이스 데이터 형식을 생성합니다.

PHP는 json 및 xml 유형 인터페이스 데이터 형식을 생성합니다.

高洛峰
高洛峰원래의
2016-12-22 14:54:14981검색

php는 인터페이스 통신 데이터를 생성합니다

/**
 * 生成接口数据格式
 */
class Response{
  /**
   * [show 按综合方式输出数据]
   * @param [int] $code    [状态码]
   * @param [string] $message [提示信息]
   * @param array $data  [数据]
   * @param [string] $type [类型]
   * @return [string]    [返回值]
   */
  public static function show($code, $message, $data = array(),$type = ''){
    if(!is_numeric($code)){
      return '';
    }
    $result = array(
      'code' => $code,
      'message' => $message,
      'data' => $data
    );
    if($type == 'json'){
      return self::json($code, $message, $data);
    }elseif($type == 'xml'){
      return self::xml($code, $message, $data);
    }else{
      //TODO
    }
  }
  /**
   * [json 按json方式输出数据]
   * @param [int] $code    [状态码]
   * @param [string] $message [提示信息]
   * @param [array] $data  [数据]
   * @return [string]     [返回值]
   */
  public static function json($code, $message, $data = array()){
    if(!is_numeric($code)){
      return '';
    }
    $result = array(
      'code' => $code,
      'message' => $message,
      'data' => $data
    );
    $result = json_encode($result);
    return $result;
  }
  
  /**
   * [xml 按xml格式生成数据]
   * @param [int] $code    [状态码]
   * @param [string] $message [提示信息]
   * @param array $data   [数据]
   * @return [string]     [返回值]
   */
  public static function xml($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;?>\n";
    $xml .= "<root>\n";
    $xml .= self::xmlToEncode($data);
    $xml .= "</root>";
    return $xml;
  }
  
  public static function xmlToEncode($data){
    $xml = &#39;&#39;;
    foreach($data as $key => $value){
      if(is_numeric($key)){
        $attr = "id=&#39;{$key}&#39;";
        $key = "item";
      }
      $xml .= "<{$key} {$attr}>\n";
      $xml .= is_array($value) ? self::xmlToEncode($value) : "{$value}\n";
      $xml .= "</{$key}>\n";
    }
    return $xml;
  }
}
//测试
$grade = array("score" => array(70, 95, 70.0, 60, "70"), "name" => array("Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "TianQi"));
$response = new Response();
$result = $response :: show(200,&#39;success&#39;,$grade,&#39;json&#39;);
print_r($result);

위 내용은 이 글의 전체 내용이므로 마음에 드셨으면 좋겠습니다.

PHP에서 json 및 xml 유형의 인터페이스 데이터 형식을 생성하는 것과 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.