php soap что такое

Работа с веб-серверами на php посредством SOAP

Не буду останавливаться на вопросе, что такое веб-сервисы и зачем они нужны. В сети очень много статей на эту тему. Просто постараюсь вкратце показать, каким простым способом возможно создание клиента к любому веб-сервису на php.

Для использования SOAP в php необходимо подключить модуль SOAP (входит в дистрибутив php5). Под windows это делается просто – необходимо дописать (именно дописать, так как эта строка там не просто закомментирована, она отсутствует вообще) в php.ini:
extension=php_soap.dll

Не забудьте перезапустить сервер, если php у вас установлен как модуль.

Создание SOAP-клиента по WSDL-документу

Создание SOAP-клиента обычно происходит по WSDL-документу, который представляет собой XML-документ в определенном формате, полностью описывающий тот или иной веб-сервис. За подробностями по поводу WSDL – отправляю Вас на сайт консорциума W3C — www.w3.org/TR/2005/WD-wsdl20-soap11-binding-20050510.

Главное же, что необходимо знать для того, чтобы построить клиента к веб-сервису – это знать URL его WSDL-документа.
Для примера возьмем веб-сервис «Currency Exchange Rate» от xmethods.com. Адрес этого веб-сервиса, который позволяет получать курсы валют в режиме онлайн — www.xmethods.net/sd/2001/CurrencyExchangeService.wsdl.

Второй важный момент – из описания веб-сервиса необходимо получить информацию о том, какие методы этот сервис предоставляет, и какие параметры мы должны передавать ему в качестве входных значений (очень похоже на вызов обычной функции php или метода класса). Обычно эта информация содержится в описании сервиса на его сайте. Наш веб-сервис для получения курса валют предоставляет метод getRate(), которому в качестве аргументов передаются коды валют.

И последнее – важно знать, что ожидать в качестве ответа: сколько значений, какого типа и т.п. Это также можно получить из описания.
А в результате код получается очень простым и компактным, почти элементарным:

Как видно из кода в конструктор класса SoapClient необходимо передать URL WSDL-документа и получить объект для работы с нужным веб-сервисом. Затем вызывается метод этого объекта, имя которого совпадает с именем самого метода веб-сервиса. Возвращает же этот метод желаемый нами результат.

Итак, этот простой пример иллюстрирует нам принцип построения SOAP-клиента для веб-сервисов на php. Однако в реальном приложении еще о многом придется позаботиться, в частности о том, что в момент обращения к веб-сервису он может быть временно недоступен или возвращать ошибку. Явно напрашивается использование блока try/catch/throw 🙂

Источник

Создание веб сервиса на PHP

Что такое веб-сервис?

Веб-служба, веб-сервис (англ. web service) — идентифицируемая уникальным веб-адресом (URL-адресом) программная система со стандартизированными интерфейсами, а также HTML-документ сайта, отображаемый браузером пользователя. (Материал из Википедии)

Иными словами Web-сервис (служба) – программа, которая организовывает взаимодействие между сайтами. Информация с одного портала передается на другой.

Например, есть авиакомпания. У нее много рейсов, соответственно, много билетов. Информацию через веб-службу она передает сайту-агрегатору тур-путешествий. Пользователь, который заходит на агрегатор, сможет прямо там купить билеты этой авиакомпании.

Другой пример веб-сервисов — это сайт отслеживания погоды, который содержит сведения о метеоусловиях в конкретном городе или по стране в целом. Данная информация также часто используется сторонними приложениями.

Информация в интернете разнородна. Сайты управляются разными системами. используются разные протоколы передачи и шифрования. Веб-сервисы упрощают обмен информацией между разными площадками.

В этой статье покажем Вам, как создать простой веб-сервис на базе Simple Object Access Protocol (SOAP).

Что такое SOAP?

php soap что такое. Смотреть фото php soap что такое. Смотреть картинку php soap что такое. Картинка про php soap что такое. Фото php soap что такое

SOAP (от англ. Simple Object Access Protocol — простой протокол доступа к объектам; вплоть до спецификации 1.2) — протокол обмена структурированными сообщениями в распределённой вычислительной среде. Первоначально SOAP предназначался в основном для реализации удалённого вызова процедур (RPC). Сейчас протокол используется для обмена произвольными сообщениями в формате XML, а не только для вызова процедур. Официальная спецификация последней версии 1.2 протокола никак не расшифровывает название SOAP. SOAP является расширением протокола XML-RPC.

SOAP может использоваться с любым протоколом прикладного уровня: SMTP, FTP, HTTP, HTTPS и др. Однако его взаимодействие с каждым из этих протоколов имеет свои особенности, которые должны быть определены отдельно. Чаще всего SOAP используется поверх HTTP.

SOAP является одним из стандартов, на которых базируются технологии веб-служб.

Источник

Php soap что такое

PROBLEM (with SOAP extension under PHP5) of transferring object, that contains objects or array of objects. Nested object would not transfer.

SOLUTION:
This class was developed by trial and error by me. So this 23 lines of code for most developers writing under PHP5 solves fate of using SOAP extension.

/*
According to specific of organization process of SOAP class in PHP5, we must wrap up complex objects in SoapVar class. Otherwise objects would not be encoded properly and could not be loaded on remote SOAP handler.

class Person extends SOAPable <
//any data
>

$PersonList =new PersonList ;

?>

So every class, which will transfer via SOAP, must be extends from class SOAPable.
As you can see, in code above, function prepareSOAPrecursive search another nested objects in parent object or in arrays, and if does it, tries call function getAsSOAP() for preparation of nested objects, after that simply wrap up via SoapVar class.

Juste a note to avoid wasting time on php-soap protocol and format support.

Until php 5.2.9 (at least) the soap extension is only capable of understanding wsdl 1.0 and 1.1 format.

The wsdl 2.0, a W3C recommendation since june 2007, ISN’T supported in php soap extension.
(the soap/php_sdl.c source code don’t handle wsdl2.0 format)

The wsdl 2.0 is juste the 1.2 version renamed because it has substantial differences from WSDL 1.1.

The differences between the two format may not be invisible if you don’t care a lot.

Источник

Класс SoapClient

Введение

Класс SoapClient представляет собой клиента для серверов » SOAP 1.1, » SOAP 1.2. Он может использоваться в режиме с WSDL или без него.

Обзор классов

Содержание

User Contributed Notes 19 notes

When you need to connect to services requiring to send extra header use this method.

Here how we can to it with PHP and SoapClient

$devKey = «» ;
$password = «» ;
$accountId = «» ;

CAUTION:
I had quite a bit of trouble trying to make a request with fopen through a proxy to a secure url. I kept getting a 400 Bad Request back from the remote host. It was receiving the proxy url as the SNI host. In order to get around this I had to explicity set the SNI host to the domain I was trying to reach. It’s apparently the issue outlined in this bug:

You need to redefine the soapClient class and force the port in each call.

There is a known bug with some versions of Xdebug which can cause SoapClient to not throw an exception but instead cause a fatal error.

Surround the SoapClient call with xdebug_disable(); and xdebug_enable(); to work around this problem.

When you get errors like:
«Fatal error: Uncaught SoapFault exception: [HTTP] Error Fetching http headers in»
after a few (time intensive) SOAP-Calls, check your webserver-config.

Sometimes the webservers «KeepAlive»-Setting tends to result in this error. For SOAP-Environments I recommend you to disable KeepAlive.

Hint: It might be tricky to create a dedicated vhost for your SOAP-Gateways and disable keepalive just for this vhost because for normal webpages Keepalive is a nice speed-boost.

when they want to pass variables into the http header that is how it is done:

[ ‘http’ ][ ‘header’ ] = «User-Agent: PHP-SOAP/5.5.11\r\n» ;

If the XML have identities with same name in different levels there is a solution. You don´t have to ever submit a raw XML (this PHP SOAP object don´t allows send a RAW XML), so you have to always translate your XML to a array, like the example below:

//Translate the XML above in a array, like PHP SOAP function requires
$myParams = array(‘firstClient’ => array(‘name’ => ‘someone’,
‘adress’ => ‘R. 1001’),
‘secondClient’ => array(‘name’ => ‘another one’,
‘adress’ => »));

Under IIS and PHP 7, when creating an new SoapClient, it will through an internal 500 error.

This could be caused by invalid permissions to the wsdl cache directory when using ‘cache_wsdl’=>WSDL_CACHE_DISK or WSDL_CACHE_BOTH.

This worked for me:
try <
$arrContextOptions=array(«ssl»=>array( «verify_peer»=>false, «verify_peer_name»=>false,’crypto_method’ => STREAM_CRYPTO_METHOD_TLS_CLIENT));

Exception Error!

If you want to connect to a server that only supports SSLv2/3 and/or TLS 1.0 (no TLS 2 or 3), tell the SOAP client if you get a connection error by setting the appropriate stream context:
= array(
‘ssl’ => array( ‘ciphers’ => ‘RC4-SHA’ )
);

There is defined the server and the cliente who calls the web service.

I hope it would be useful for you.

slow SOAP servers.
As for the KeepAlive, if creating a new separate vhost for the soap api is not possible, you can add this to your existing vhost: BrowserMatch «^PHP-SOAP» nokeepalive
where PHP-SOAP is the agent name of your soap client, if you dont know what agent name your client use, just checkout the access.log of your apache.

To make an HTTPS call with a client certificate, you can do it this way:

——BEGIN RSA PRIVATE KEY——
MIICXAIBAAKagQC1N27Ilb9pWil2NaX2qM8FquXBXK5T1AydOv7sCotsc8MAwbi7
. (snip).
wAiOCD4K9TyMS76pIS8UyfJl/oIrn7EF24BUpaUfsh8=
——END RSA PRIVATE KEY——
——BEGIN CERTIFICATE——
MIIC/zCCAmigAwIBAgIEAIl1JzANBgkqhkiG9w0BAQQuADBQMQswCQYxVQQGEaJV
. (snip).
eSPds1hLKYSg0bd3uI7LhaDLOC1PPgb77sYe/uYkUWuHBzllts5x/pfue0zaIBKG
Omjy
——END CERTIFICATE——

2) Reference your certificate in the creation of the SOAP client, like this:

$protected_url = «https://my-server/?wsdl»;
$my_cert_file = «/my/path/to/mycert.pem»;

This one drove me nuts. if you are connecting to a web service run on Cassini, (Visual Studio’s web server) from php, you may not be able to call web service functions or load a WSDL out-of-the-box.

My set up is that I am using xampp on my windows development machine, and also using Visual Studio’s built in web-server. I built a web service in visual studio. I wrote a simple PHP script, running under xampp, to access this service, so the two projects can ‘talk’ to each other. What I found was the WSDL was never loaded.

So I moved the WSDL local to the PHP file and accessed it directly. Still no calls. Turns out, PHP’s SoapClient seems to have a problem with ‘localhost’ as a web service endpoint. So I hand-edited the web service endpoint URL to read 127.0.0.1 instead of localhost, and Voila! Web Service calls work:

I got the following error when trying to load the WSDL file:

Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: ‘MessageName’ already defined

I resolved it by loading the WSDL in SoapUI, right-clicking and selecting «Export definition». The WSDL that then got created worked fine. Hope this helps somebody.

when they want to pass variables into the http header that is how it is done:

[ ‘http’ ][ ‘header’ ] = «User-Agent: PHP-SOAP/5.5.11\r\n» ;

Источник

Функции SOAP

Содержание

User Contributed Notes 30 notes

Here are 73 test cases that detail the kinds of schemas that PHP5 currently supports and the structures you are expected to plug into them for the return value from your services. Much better than trying to guess!

You can cycle through the listings by changing the main index in the URL below, rather than go in and out of the pages

I downloaded the whole thing with this, CVS might work too.
http://www.httrack.com/

With them all downloaded I just browse them with Textpad.

when naming definitions,
don’t use «tns:» but use «typens:»

makesure your «definitions/targetNamespace»
is same as your «soap:body» namespace
example: «urn:mynamespace»

makesure your «binding/type» is declared with «typens»

makesure your service/port/binding is set to ‘typens. ‘

happy coding 🙂
hope this help you to save your time on the wsdl 🙂

If you dont want to manually maintain the classmap, make sure you use the same names for your PHP object classes and your WSDL complexTypes, and use the following code:

$classmap = array();
$tmpClient = new SoapClient(«soapserver.wsdl»);

I hope this will save someone time. When developing and testing your SOAP server, remember to disable WSDL caching in BOTH client and server:

$ini = ini_set(«soap.wsdl_cache_enabled», 0);

Wondering why the function you just added to your WSDL file is not available to your SOAP client? Turn off WSDL caching, which (as the documentation says) is on by default.

At the top of your script, use:

Having trouble passing complex types over SOAP using a PHP SoapServer in WSDL mode? Not getting decoded properly? This may be the solution you’re looking for!

* First, define a specific PHP class which is actually just a data structure holding the various properties, and the appropriate ComplexType in the WSDL.

* Next, Tell the SoapServer when you initialize it to map these two structures together.

public function MySoapCall () <
$o = new MyComplexDataType ();

replace ‘soapclient’ with ‘soapclient_xxx’ in nusoap.php and you are good to go.

When encountering an error message like this

[faultstring] => Function («yourMethod») is not a valid method for this service

although it is present in the WSDL etc., be aware that PHP caches the wsdl locally for better performance. You can disable the caching via php.ini/.htaccess completely or remove the cache file (/tmp/wsdl-.. if you are on Linux) to force regeneration of it.

If you are working
— on localhost
— in WSDL mode
and encounter the following error when you try to connect the soap client with the soap server

Fatal error: Uncaught SoapFault exception: [HTTP] Could not connect to host.

then change «localhost» to «127.0.0.1» in your WSDL file:

Heads up for anyone using PHP Soap + Sessions + PEAR DB classes.

Every time you make a call, via the soap client to your web service, your PEAR DB session is put to sleep and it doesnt by default wake upon the next request.

For those wondering on how to set attributes on nodes with PHP5 SOAP, it would be done as such:

array(«foo» => array(«_» => 12345, «bar» => «blah»));

If you use SSL with a cert and password authentication:

If you have problems with the certfile like this:

Warning: SoapClient::__construct(): Unable to set local cert chain file `./mycert.pem’; Check that your cafile/capath settings include details of your certificate and its issuer in productinfo.php on line 27

then the certFile is probably in the «wrong format» (the wrong format for php maybe). It worked for me, when i appended the content of the private key file and the certificate file to a single file «mycert.pem»:

cat mycert.key >mycert.pem # mycert.key was the private key
cat mycert.crt >>mycert.pem # mycert.crt was the signed certificate

this might be helpful, as it took quite some time for me to find this out:

wow, actually a cool program and soap is new for me.
I found out some interessting things i can not debug because the scripts exit without any error messages or notes. 🙁

you may have problems with the memory and/or especially on «shared servers» when server load is high.
sometimes the script does the job, sometimes it just stopping at any unknown point.
these are the steps my script does:
* get data from remote server (

4.5 MB)
* parsing requested object and store the data in a database.

so, and if now someone on the server takes the rest of RAM the walk thought the data breaks 🙁

so, i need to store the xml tree ($client->client->__last_response) and parsing it by the classical way. (if you would request more RAM, you may get in trouble with the admin if you run a script like this more often! (on shared servers)

For those working from a wsdl full of complex types that just want a class structure to hang your code on and not worry about typing in long parameter lists (or creating a script to do so): wsdl2php is a wonderful time-saver. Gets a structure going so you can go in and add what validation and special data munging you need: http://www.urdalen.no/wsdl2php/

Big up yourself, Knut.

I have PHP 5.2.5 on my computer. I get this result:

Array
(
[0] => stdClass Object
(
[Client] => stdClass Object
(
[Nom] => LeNom:00000
[Prenom] => LePrenom:00000
)

My host have 5.1.6, the same call returns this result:
Array
(
[0] => stdClass Object
(
[Client] => Array
(
[0] => stdClass Object
(
[Nom] => LeNom:00000
[Prenom] => LePrenom:00000

5.2.5 is the good structure.

Take care of the version you’re using. It can be a lot of work to change all the code

PROBLEM (with SOAP extension under PHP5) of transferring object, that contains objects or array of objects. Nested object would not transfer.

SOLUTION:
This class was developed by trial and error by me. So this 23 lines of code for most developers writing under PHP5 solves fate of using SOAP extension.

/*
According to specific of organization process of SOAP class in PHP5, we must wrap up complex objects in SoapVar class. Otherwise objects would not be encoded properly and could not be loaded on remote SOAP handler.

class Person extends SOAPable <
//any data
>

$PersonList =new PersonList ;

?>

So every class, which will transfer via SOAP, must be extends from class SOAPable.
As you can see, in code above, function prepareSOAPrecursive search another nested objects in parent object or in arrays, and if does it, tries call function getAsSOAP() for preparation of nested objects, after that simply wrap up via SoapVar class.

Just a note on «DTD not recognised. » faults. Check to make sure your wsdl file contains:

Also make sure you use full paths, to your service (in the wsdl, client and server)
.

.
// SOAP Server
$server = new SoapServer ( ‘http://www.mysite.com.au/web_services/hello.wsdl’ );
.
.
?>

// SOAP Client
$client = new SoapClient ( ‘http://www.mysite.com.au/web_services/hello.wsdl’ );
.
.
?>

FYI im no SOAP expert but I hope this helps someone out 😉

Thought it would be worth it to share. What it is saying is that there is some text in an invalid place. C# seems to ignore it, and if you are using nusoap it doesn’t notice it either. But what was causing my problem was something like:

;

Note the semicolon (;). Filter that out and your good.

makesure you define the input correctly.
if your method does not contain any input parameter,
you got to makesure that you:

— do not create the message tag for the input..
— do not put input within porttype / operation
— do not put input within binding / operation

if not, you will get the error:
[Client] looks like we got no XML

d***, took me several hours figuring that out.

= «test.wsdl» ;
$local_cert = «c:\htdocs\mycert.pem» ;
$passphrase = «xyz» ;

If you want to build a Soap Server for Microsoft Office’s client (like Microsoft Office Research Service) you need to rewrite SOAP’s namespaces :

Here’s an example on how to pass ArrayOfAnyType arguments
containing complex types.

Suppose your WSDL file defines «http://any.url.com/» as the default namespace and a complex type «SomeComplexType».

If you want to call a WebServices which takes an ArrayOfAnyType argument of «SomeComplexType»s you need to perform the following:

// complexTypes being an array containing several instances of SomeComplexType

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *