PHP implementation of simple mock JSON script sharing, Phpmockjson script
There are now too many ways to mock, but it might be easier to use this as a temporary mock-up when it is time to connect to the remote server to test the true return, if there is no node on the machine and PHP.
Copy CodeThe code is as follows:
<?php
/**
* Mock Json for Javascript
*
* @author Soulteary
* @date 2014-06-15
*/
/**
* Request Interface field: Character set
*/
Define (' CharSet ', ' CharSet ');
/**
* Request Interface Field: callback function name
*/
Define (' Callback ', ' callback ');
/**
* Request interface fields: cross-domain fields
*/
Define (' Crossdomain ', ' cross-domain ');
/**
* Output mock data
* If a Mock.json file exists, the data is retrieved from the Mock.js
*
* @return String
*/
Functionmockdata ()
{
if (file_exists (' Mock.json ')) {
$data =json_decode (file_get_contents (' Mock.json '));
}else{
$data =array (
' Code ' =>200,
' desc ' = ' Get the default data. '
' Login ' =>true,
' Data ' =>array (
' Name ' = ' + ' Test API. '
)
);
}
Returnjson_encode ($data);
}
/**
* Output character set, allowing results of GBK, gb2312, Utf-8
* If illegal or not set, output utf-8
*
* @return String
*/
Functioncharset ()
{
$ret = ' utf-8 ';
if (empty ($_request[charset])) {
Return$ret;
}else{
$charset =strtolower ($_request[charset]);
if (In_array ($charset, Array (' GBK ', ' gb2312 '), true)) {
Return$charset;
}else{
Return$ret;
}
}
}
/**
* Assemble JSON data
*
* @return String
*/
Functionjsongenerator ()
{
if (!empty ($_request[callback])) {
Header (' Content-type:application/javascript; charset= '. CharSet ());
Return$_request[callback]. " (". Mockdata ()."); ";
}else{
if (!empty ($_request[crossdomain])) {
Header ("Access-control-allow-origin: *");
};
Header (' Content-type:application/json; charset= '. CharSet ());
Returnmockdata ();
}
}
/**
* Output Results
*/
Die (Jsongenerator ());
If you do not want to change the PHP data object, feel trouble, then directly change the JSON well, you may ask, then why I do not directly access a JSON it, a:
1. You may need a callback package for this result;
2. You may expect this JSON to allow cross-domain requests;
3. You may expect this JSON to customize the header code ...
Copy the Code code as follows:
{
"Data": 1,
"W": "Test"
}
The code is simple, so it's not too much to describe.
http://www.bkjia.com/PHPjc/955975.html www.bkjia.com true http://www.bkjia.com/PHPjc/955975.html techarticle PHP Implementation of the simple mock JSON script to share, Phpmockjson script now has too many ways to mock, but when still want to connect to the remote server to test the real return time, if the machine ...