Heim >Backend-Entwicklung >PHP-Tutorial >php写webservice接口

php写webservice接口

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-29 09:04:213306Durchsuche

用php写api大部分都是基于http请求的api接口,有时候项目中就让你用php写webservice接口。

那就要用到php的扩展soap.

什么是soap?

Simple Object Access Protocol 简单对象访问协议
主要包括下面四部分:
a) SOAP 封装: 用于将传输数据中的内容, 发送端消息, 接收端信息和处理方式等信息封装起来以准备数据传输.
b) SOAP 编码规则: 用于表示传输数据中各项的数据类型等信息
c) SOAP 远程过程调用协定: 用于进行远程过程调用及应答的协议

1.要配置php.ini打开soap扩展:extension=php_soap.dll; 去掉前面的;

2.写服务端server.php 这里我用的传输数据为json

代码:

$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接口
 * @param array json 
 */
function api_test($num){
    $num=json_decode($num,1);
$num['res']=$num['num1']+$num['num2'];
return json_encode($num,1);
}

3.写客户端代码,这里也是用json作为传输数据:

代码:

/**
 * 测试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.在浏览器中输入localhost/client.php调用接口会得到:

php写webservice接口

php webservice接口OK!

以上就介绍了php写webservice接口,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn