This article mainly introduces the simple mockjson script for PHP implementation. This article provides the implementation code directly. If you need it, you can refer to there are too many methods to go to mock, however, if you still want to connect to the remote server to test the true response, if the node is not run on the machine and php is available, use this product to temporarily mock it, which may be easier.
The 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 Field: Cross-origin Field
*/
Define ('crossdomain ', 'cross-domain ');
/**
* Output mock data
* If the mock. json file exists, the data is obtained from mock. js.
*
* @ Return string
*/
FunctionmockData ()
{
If (file_exists ('mock. json ')){
$ Data = json_decode (file_get_contents ('mock. json '));
} Else {
$ Data = Array (
'Code' = & gt; 200,
'Desc' => 'get the default data .',
'Login' => true,
'Data' => Array (
'Name' => 'test api .'
)
);
}
Returnjson_encode ($ data );
}
/**
* Output character set, which can return gbk, gb2312, and UTF-8
* If it is invalid or not set, UTF-8 is output.
*
* @ 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 result
*/
Die (jsonGenerator ());
If you don't want to change the data object in php, you may want to change the json directly. Why don't I directly access a json file?:
1. You may need a callback to wrap this result;
2. You may expect this json to allow cross-origin requests;
3. You may expect this json to be able to customize the header encoding...
The Code is as follows:
{
"Data": 1,
"W": "test"
}
The code is very simple, but it is not described much.