SOAP - WSDL - PHP

Что такое SOAP?
SOAP представляют Простой Протокол Объектного Доступа
SOAP является протоколом связи
SOAP для связи между приложениями
SOAP - формат для посылки сообщений
SOAP предназначен для связывания через Internet
SOAP кроссплатформенный
SOAP является языково-независимым
SOAP основан на XML
SOAP простой и расширяемый
SOAP позволяет Вам обходить файрволы
SOAP будет разработан как стандарт W3C
--------------------------------------------------------------------------------
Почему SOAP?
Важно для прикладной разработки допускать связь Internet между программами.
Сегодняшние приложения обычно юзают Удаленный Вызов Процедур (Панель управления-Службы-svchost.exe, RPC) между объектами подобно DCOM и CORBA, но HTTP не был разработан для этого. RPC представляет проблему совместимости и безопасности; файрволы и прокси обычно блокируют этот тип трафика.
Лучший путь связываться между приложениями - через HTTP, поскольку HTTP поддерживан всеми браузерами и Internet-серваками. SOAP был создан, чтобы выполнять именно это, ребята!!! Ура!
SOAP обеспечивает путь для общения между приложениями, работающими на других операционных системах, с другими технологиями и языками программирования.

 

This post will show a simple example of how to interpretate a WSDL file and a very simple, yet quick example of how to extract information from this file through PHP.

Prior assumptions

In this example I assume that you've already have SOAP enabled in your PHP configuration because this is beyond the scope of this example. If you're not sure, you can check your phpinfo file. There should be something like this:


SOAP information

 

Example WSDL file

For the example WSDL file we'll take this WSDL file. It's about the World Championship football 2010 held in South Africa.

Analyzing the WSDL file

Let's analyze this file for a simple method we can call. I usually work with Notepad++ or Smultron. The following line number apply to Notepad++ and probably also to Smulton.

Let's try and print the top goal scorers of the tournament. For doing this, we can see the following on line 1295 - 1300:

1 <operation name="TopGoalScorers">
2   <documentation>
3 Returns an array with the top N goal scorers and their current score. Pass 0 as TopN and you get them all.
4   documentation>
5   <input message="tns:TopGoalScorersSoapRequest"/>
6   <output message="tns:TopGoalScorersSoapResponse"/>
7 operation>

We now see that the operation we should call is called TopGoalScorers. This operation expects as input a TopGoalScorersSoapRequest. We don't know what it is yet, so let's find out. If we search the document for this message, we get to line 999 - 1002 which says:

1 <message name="TopGoalScorersSoapRequest">
2   <part name="parameters" element="tns:TopGoalScorers" />
3 message>

Right. So now we know that the TopGoalScorersSoapRequest consists of just one part (the parameters). We know that the element is called TopGoalScorers, but we do not know anything about this parameter yet. So we search the document for the element TopGoalScorers. We can find this element at line 384 - 390. These lines say

1 <xs:element name="TopGoalScorers">
2   <xs:complexType>
3     <xs:sequence>
4       <xs:element name="iTopN" type="xs:int" />
5     xs:sequence>
6   xs:complexType>
7 xs:element>

Now there we have it: we now finally know that the method TopGoalScorers which we saw in the first WSDL fragment expects one parameter as input. This parameter is called iTopN and is of the type int.

Getting to the code

Finally we can do something with the WSDL. Actually we can do this in a very short way thanks to the PHP SoapClient!

Calling the service with the parameter and obtaining the results can be done in just 2 lines of code. Let's give it a try and obtain the top 5 goal scorers. We can do this by the following two lines:

2 $result = $client->TopGoalScorers(array('iTopN'=>5));

Note that we use the information we obtained from the WSDL file here: on the $client object, we call the method TopGoalScorers and provide an array of parameters. In this case the array contains only one parameter: the iTopN parameter with an int value of 5.

The result will contain an object, so you will need to traverse the object structure.

Choose how much results

There are a lot of possibilities for abstracting such a Web Service call further. I will just give a very simple example file where you can choose how many results you want to see and visualize this in a table.

Code:

<?php

if ($_POST['topn'] > 0 && (int) $_POST['topn'] <= 20){
  $topn = (int) $_POST['topn'];
  $client = new SoapClient("http://footballpool.dataaccess.eu/data/info.wso?wsdl");
  $result = $client->TopGoalScorers(array('iTopN' => $topn));
  // Note that $array contains the result of the traversed object structure
  $array = $result->TopGoalScorersResult->tTopGoalScorer;

  print "
    
  ";
  
  foreach($array as $k=>$v){
    print "
      ";
  }
  
  print "
Rank Name Goals
" . ($k+1) . " " . $v->sName . " " . $v->iGoals . "
"; } else { ?>
How long should your topscorers list be? (Choose a digit between 1 and 20).

Note that the form calls index.php. This is because I called this script index.php. If you call your script differently, the action should be your script file name. (The reason why I didn't use $_SERVER['PHP_SELF'] is because of this Dutch source about how this element can cause an XSS problem).

I hope you found the example useful. If not, let me know! Now go and play with PHP, SOAP and WSDL some more!

Edit 11/08/2010: Noticed that the WSDL was removed. Changed to WC 2010 WSDL file which seems to have the same format as the original WSDL.

Оригинал тут: http://www.vankouteren.eu/blog/2009/03/simple-php-soap-example/

http://www.lifeinet.ru/index.php?id=695

Scroll to Top
Ads: