PHP笔记PHP实战

php soap操作

2017-09-20  本文已影响77人  零一间

简介

SOAP 简单对象访问协议是交换数据的一种协议规范,是一种轻量的、简单的、基于XML(标准通用标记语言下的一个子集)的协议,它被设计成在WEB上交换结构化的和固化的信息。

SOAP(Simple Object Access Protocol )简单对象访问协议是在分散或分布式的环境中交换信息的简单的协议,是一个基于XML的协议,它包括四个部分:

优点

SOAP有两种操作方式,NO-WSDL 与 WSDL

SOAP中主要用到三个类,SOAPServer,SOAPClient,SOAPFault.

简单示例:

server.php

<?php

class soapHandle
{

    public function strtolink($url = '') {
        return sprintf('<a href="%s">%s</a>', $url, $url);
    }
}

try {
    $server = new SOAPServer(null, ['uri' => 'http://127.0.0.1:8002/demo/soap/NO-WSDL/server.php']);
    $server->setClass('soapHandle');
    $server->handle();
} catch (SOAPFault $f) {
    echo $f->getMessage();
}

client.php

<?php

try {
    $client = new SOAPClient(null, [
        'location' => 'http://127.0.0.1:8002/demo/soap/NO-WSDL/server.php',
        'uri'      => 'http://127.0.0.1:8002/demo/soap/NO-WSDL/server.php',
    ]);

    // 直接调用
    echo $client->strtolink('www.demo.com') . '<br>';
    // 间接调用
    echo $client->__soapCall('strtolink', ['www.demo.com']);

} catch (SOAPFault $e) {
    echo $e->getMessage();
}

简单示例升级

server.php


<?php

class SOAPHandle
{

    public function auth($auth) {
        if ($auth->string[0] != 'demo' || $auth->string[1] != '123456') {
            throw new SOAPFault('Server', 'No Permission');
        }
    }

    public function strtolink($str = '', $name = '', $openwin = 0) {
        $name = $name == '' ? $str : $name;
        $openwin_tag = $openwin == 1 ? ' target="_blank" ' : '';

        return sprintf('<a href="%s" %s>%s</a>', $str, $openwin_tag, $name);
    }

}

$config = array(
    'uri' => 'http://127.0.0.1:8002/demo/soap/NO-WSDL-Header/server.php'
);

$objHandle = new SOAPHandle;

// no wsdl mode
try {

    $server = new SOAPServer(null, $config);
    $server->setObject($objHandle );
    $server->handle();

} catch (SOAPFault $f) {

    echo $f->faultString;

}

client.php

<?php

$config = [
    'location' => 'http://127.0.0.1:8002/demo/soap/NO-WSDL-Header/server.php',
    'uri'      => 'http://127.0.0.1:8002/demo/soap/NO-WSDL-Header/server.php',
    'trace'    => true
];

try {

    $auth = [
        'demo',
        '123456'
    ];

    // no wsdl
    $client = new SOAPClient(null, $config);

    /*
     * SoapHeader参数说明如下所示:
     * 'http://tempuri.org/'   namespace(命名空间可省略)
     * 'MySoapHeader'          SoapHeader头的类名
     * 'array(...)'            存放标识身份的字符串参数
     * 'true'                  是否必须处理该header
    */
    $header = new SOAPHeader('http://127.0.0.1:8002/demo/soap/NO-WSDL-Header/server.php', 'auth', $auth, false, SOAP_ACTOR_NEXT);
    $client->__setSoapHeaders([$header]);

    $strtolink = $client->__soapCall('strtolink', [
        'http://www.demo.com',
        '测试网址',
        1
    ]);
    echo $strtolink . '<br>';

} catch (SOAPFault $e) {
    echo $e->getMessage();
}

参考
浅谈 SOAP

上一篇 下一篇

猜你喜欢

热点阅读