search
HomeBackend DevelopmentPHP Tutorialphp实现的返回数据格式化类实例_php技巧

本文实例讲述了php实现的返回数据格式化类及其用法,在字符串处理中非常具有实用价值。分享给大家供大家参考。具体方法如下:

DataReturn.class.php类文件如下:

<&#63;php 
/** 返回数据格式化类 
*  Date:  2011-08-15 
*  Author: fdipzone 
*/ 
 
class DataReturn{  // class start 
 
  private $type; 
  private $xmlroot; 
  private $callback; 
  private $returnData; 
 
  public function __construct($param=array()){ 
    $this->type = $this->exists($param,'type')&#63; strtoupper($param['type']) : 'JSON';   // 类型 JSON,XML,CALLBACK,ARRAY 
    $this->xmlroot = $this->exists($param,'xmlroot')&#63; $param['xmlroot'] : 'xmlroot';   // xml root dom name 
    $this->callback = $this->exists($param,'callback')&#63; $param['callback'] : '';     // JS callback function name 
 
    $format = array(); 
    $format['retcode'] = $this->exists($param,'format.retcode')&#63; $param['format']['retcode'] : 'retcode';//retcode 对应名称 
    $format['msg'] = $this->exists($param,'format.msg')&#63; $param['format']['msg'] : 'msg';        //msg 对应名称 
    $format['data'] = $this->exists($param,'format.data')&#63; $param['format']['data'] : 'data';      //data 对应名称 
 
    $result = array(); 
    $result[$format['retcode']] = $this->exists($param,'retcode')&#63; $param['retcode'] : 0; 
    $result[$format['msg']] = $this->exists($param,'msg')&#63; $param['msg'] : ''; 
    $result[$format['data']] = $this->exists($param,'data')&#63; $param['data'] : ''; 
 
    $this->returnData = $result; 
  } 
 
  //输出数据 
  public function data_return(){ 
    ob_clean(); 
    switch($this->type){ 
      case 'JSON': 
        $this->json_return(); 
        break; 
      case 'XML': 
        $this->xml_return(); 
        break; 
      case 'CALLBACK': 
        $this->callback_return(); 
        break; 
      case 'ARRAY': 
        $this->array_return(); 
        break; 
      default: 
        $this->json_return(); 
    } 
    exit(); 
  } 
 
  //输出JSON格式数据,如有callback参数则返回JSONP格式 
  private function json_return(){ 
    header('content-type:text/html;charset=utf-8'); 
    if(empty($this->callback)){ 
      echo json_encode($this->returnData); 
    }else{ 
      echo $this->callback.'('.json_encode($this->returnData).');'; 
    } 
  } 
 
  //输出XML格式数据 
  private function xml_return(){ 
    header('content-type:text/xml;charset=utf-8'); 
    echo $this->xml_encode($this->returnData,$this->xmlroot); 
  } 
 
  //输出JSON格式数据,并调用callback方法 
  private function callback_return(){ 
    header('content-type:text/html;charset=utf-8'); 
    $this->callback = empty($this->callback)&#63; 'callback' : $this->callback; 
    echo "<script type=\"text/javascript\">\r\n"; 
    echo $this->callback."(".json_encode($this->returnData).");\r\n"; 
    echo "</script>"; 
  } 
 
  //输出数组格式数据 
  private function array_return(){ 
    header('content-type:text/html;charset=utf-8'); 
    echo '<pre class="brush:php;toolbar:false">'; 
    print_r($this->returnData); 
    echo '
'; } //XML编码 private function xml_encode($data, $root='xmlroot', $encoding='utf-8') { $xml = "\n"; $xml.= "\n"; $xml.= $this->data_to_xml($data); $xml.= "" . $root . ">"; return $xml; } //数组转XML格式 private function data_to_xml($data) { if (is_object($data)) { $data = get_object_vars($data); } $xml = ''; foreach ($data as $key => $val) { is_numeric($key) && $key = "item id=\"$key\""; $xml.=""; $xml.= ( is_array($val) || is_object($val)) ? $this->data_to_xml($val) : $this->cdata($val); list($key, ) = explode(' ', $key); $xml.="$key>\n"; } return $xml; } //判断数据是否存在 private function exists($obj,$key=''){ if($key==''){ return isset($obj) && !empty($obj); }else{ $keys = explode('.',$key); for($i=0,$max=count($keys); $i标记 private function cdata($val){ if(!empty($val) && !preg_match('/^[A-Za-z0-9+$]/',$val)){ $val = ''; } return $val; } } // class end ?>

demo示例程序如下:

<&#63;php 
  require_once('DataReturn.class.php'); 
  $param = array( // DataReturn 参数 
          'type'  => 'JSON', // 输出的类型 JSON,XML,CALLBACK,ARRAY 默认为 JSON 
          'retcode' => '1000', // retcode 的值,默认为0 
          'msg'   => '',   // msg 的值,默认为空 
          'data'  => array( // 要输出的数据 
                  'id'   => '100', 
                  'name'  => 'fdipzone', 
                  'gender' => 1, 
                  'age'  => 28 
                 ), 
          'format' => array( // 输出的数据key格式,默认为 retcode,msg,data 
                  'retcode' => 'status', 
                  'msg'   => 'info', 
                  'data'  => 'result' 
                 ), 
          'xmlroot' => 'xmlroot', // 当type=XML时,XML根节点名称,默认为xmlroot 
          'callback' => 'callback' /* 回调方法名称 
                          type=JSON时,默认为空,如不为空,则输出callback({data}); 
                          type=CALLBACK时,默认为callback,自动调用页面JS回调方法 
                       */ 
  ); 
  $obj = new DataReturn($param); // 创建DataReturn类对象 
  $obj->data_return();      // 按格式输出数据 
&#63;>

希望本文所述对大家php程序设计的学习有所帮助。

Statement
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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.