Most APIs written in PHP are based on HTTP request API interfaces. Sometimes the project will ask you to write webservice interfaces in PHP.
Then you need to use the PHP extension soap.
What is soap?
Simple Object Access Protocol Simple Object Access Protocol
mainly includes the following four parts:
a) SOAP encapsulation: used to transfer transmission Information such as the content of the data, the sender's message, the receiver's information and processing methods are encapsulated to prepare for data transmission.
b) SOAP encoding rules: used to represent the data type and other information of each item in the transmitted data
c ) SOAP Remote Procedure Call Protocol: A protocol used for remote procedure calls and responses
1. To configure php.ini to open the soap extension: extension=php_soap.dll; Remove the previous;
2. Write server.php. The transmission data I use here is json
Code:
$soap = new SoapServer(null,array('uri'=>"http://192.168.30.120/"));//ip adr
$soap->addFunction('api_test');
$soap-> addFunction(SOAP_FUNCTIONS_ALL);
$soap->handle();
/**
* api interface
* @param array json
*/
function api_test($num){
$num=json_decode($num,1);
$num['res ']=$num['num1']+$num['num2'];
return json_encode($num,1);
}
3. Write client code, json is also used here as Transfer data:
Code:
/**
* Test php webservice
* @param array json
*/
try {
$client = new SoapClient(null,
array('location' => ;"http://192.168.30.120/server.php",'uri' => "http://127.0.0.1/")
);
$num['num1']=1;
$num[ 'num2']=2;
$num=json_encode($num,1);
$rs=$client->api_test($num);
echo $rs;
echo "";<br>print_r (json_decode($rs,1));<br>echo "
} catch (SoapFault $fault){
echo "Error: ",$fault->faultcode,", string: ",$ fault->faultstring;
}
?>
4. Enter localhost/client.php in the browser to call the interface and you will get:
php webservice interface OK!
The above has introduced the webservice interface written in PHP, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.