PHP implementation returns JSON and XML class sharing _php tips

Source: Internet
Author: User

The code is very concise, function is also very simple and practical, here is not much nonsense, directly to the code:

Copy Code code as follows:

<?php
Class reponse{
Private $result = Array (' Code ' =null, ' message ' =null, ' data ' =>null);
/**
* @desc return JSON format
* @param int $code
* @param string $message
* @param array $data
* Return string
*/
public static function JSON ($code, $message = null, $data = Array ()) {
if (!is_numeric ($code)) {
return false;
}
$result = Array (
' Code ' => $code,
' Message ' => $message,
' Data ' => $data
);
Return Json_encode ($result);
Exit
}
/**
* @desc return XML Format data
* @parma int $code Status code
* @param string $message hints
* @param array $data data
* Return string
*/
public static function XML ($code, $message = ', $data = Array ()) {
if (!is_numeric ($code)) {
return false;
}
$result = Array (
' Code ' => $code,
' Message ' => $message,
' Data ' => $data
);
$xml = ';
$xml. = "<?xml version= ' 1.0 ' encoding= ' UTF-8 '" >\n ";
$xml. = "<root>\n";
$xml. = Self::xmlencode ($result);
$xml. = "</root>";
Header ("Content-type:text/xml");
Echo $xml;
}
public static function Xmlencode ($result) {
$xml = $attr = ';
foreach ($result as $key => $val) {
if (Is_numeric ($key)) {
$attr = "id= ' {$key} '";
$key = "item{$key}";
}
$xml. = "<{$key} {$attr}>";
$xml. = Is_array ($val)? Self::xmlencode ($val): $val;
$xml. = "</{$key}>\n";
}
return $xml;
}
}
$data = Array (
' ID ' =>1,
' Age ' =>20,
' username ' => ' Tim ',
' Others ' =>array (1,2,3),
);
Reponse::xml (' success ', $data);
Reponse::json (' success ', $data);

Small partners can be used directly, using the method at the bottom of the code:)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.