php 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.
Использование SOAP в PHP
Рассмотрим пример, как использовать SOAP в PHP. Использование SOAP в PHP может показаться трудным, и неудобным, однако немного разобравшись, вы сразу же поймете что это не так. Если у вас возникла необходимость воспользоваться протоколом SOAP, то данный пример вам будет в помощь.
Перед использованием классов SOAP библиотека должна быть предварительно подключена в PHP. Как установить PHP Soap на сервер CentOS Linux ранее уже был пост об этом. Приступим непосредственно к примеру.
В нашем примере есть некий удаленный сервер SOAP, к которому мы будем обращаться с нашего PHP — скрипта. Нам необходимо заполучить какие-либо данные, со стороны сервера SOAP. Традиционно SOAP предназначался для реализации RPC (удаленный вызов процедур). Это говорит о том, что чтобы получить какие-то данные, на другой стороне мы будем иметь дело с чем-то вроде функции, к которой будем обращаться по имени, отправляя предустановленные параметры. В качестве успешного выполнения мы будем получать данные в виде объекта. С объектами мы так же можем привычно работать в PHP, что весьма удобно.
Как видно из примера ничего космического. Сперва мы подключаемся к серверу, для этого при создании объекта класса SoapClient мы передаем три параметра: URL сервера, логин и пароль. Далее обращаемся к функции, в нашем случае она называется GetOrderInfo, именоваться она может как угодно, и принимать различные параметры. Находиться данная функция на стороне SOAP сервера. В примере мы передаем на сервер код, по которому нам должен вернуться объект с данными. Далее мы просто выводим эти данные. Этот пример прост, и он больше для демонстрации обмена данными между 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 🙂
Функции 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
Что такое SOAP?
Объясните, пожалуйста, простыми словами, что такое SOAP, для чего нужен, и, если можно, пару примеров использования.
6 ответов 6
Лирическая часть.
Представьте что у вас реализована или реализуется некая система, которая должна быть доступна извне. Т.е. есть некий сервер, с которым вам надо общаться. Например веб-сервер.
Этот сервер может выполнять множество действий, работать с базой, выполнять какие-то сторонние запросы к другим серверам, заниматься каким-то вычислениями и т.д. жить и возможно развиваться по ему известному сценарию (т.е. по сценарию разработчиков). С таким сервером общаться человеку неинтересно, потому что он может не уметь/не хотеть отдавать красивые странички с картинками и прочим юзер-френдли контентом. Он написан и работает чтобы работать и выдавать на запросы к нему данные, не заботясь, чтоб они были человекочитаемые, клиент сам с ними разберется.
Практическая часть.
Веб-сервис (так называется то, что предоставляет сервер и то, что используют клиенты) дает возможность общения с сервером четко структурированными сообщениями. Дело в том, что веб-сервис не принимает абы какие данные. На любое сообщение, которое не соответствует правилам, веб-сервис ответит ошибкой. Ошибка будет, кстати, тоже в виде xml с четкой структурой (чего нельзя сказать правда о тексте сообщения).
WSDL (Web Services Description Language). Правила, по которым составляются сообщения для веб-сервиса описываются так же с помощью xml и также имеют четкую структуру. Т.е. если веб-сервис предоставляет возможность вызова какого-то метода, он должен дать возможность клиентам узнать какие параметры для данного метода используются. Если веб-сервис ждет строку для метода Method1 в качестве параметра и строка должна иметь имя Param1, то в описании веб-сервиса эти правила будут указаны.
Для клиентов достаточно знать url веб-сервиса, wsdl всегда будет рядом, по которому можно получить представление о методах и их параметрах, которые предоставляет этот веб-сервис.
Какие плюсы у всех этих наворотов:
Описание, имеющее четкую структуру, читается любым soap-клиентом. Т.е. какой бы ни был веб-сервис, клиент поймет какие данные веб-сервис принимает. По этому описанию клиент может построить свою внутреннюю структуру классов объектов, т.н. binding’и. В итоге программисту, использующему веб-сервис, остается написать что-то типа (псевдокод):
Минусов тоже полно:
В качестве примера есть открытый веб-сервис belavia:
Можете вручную создать и послать запрос типа:
ЗЫ Раньше был открыт веб-сервис аэрофлота, но после того как 1C добавили поддержку soap в 8ку, куча 1с-бета-тестеров с успехом положили его. Сейчас что-то там поменяли (адреса не знаю, можно поискать, если интересно).
ЗЗЫ Дисклеймер. Рассказал на бытовом уровне. Пинать можно.