2009-01-22 15 views
42

¿Alguien sabe cómo puedo publicar una solicitud SOAP desde PHP?Cómo publicar solicitud SOAP desde PHP

+0

Aquí es un buen ejemplo: http://stackoverflow.com/questions/7120586/soap-request-in-php – Iladarsda

+0

Tener nos fijamos en 'documentación php.net'? Comience [aquí] (http://php.net/manual/en/ref.soap.php) y más precisamente [aquí] (http://php.net/manual/en/function.soap-soapclient-dorequest .php) Keltia

Respuesta

3

Es posible que desee mirar here y here.

Un ejemplo de código poco desde el primer eslabón:

<?php 
// include the SOAP classes 
require_once('nusoap.php'); 
// define parameter array (ISBN number) 
$param = array('isbn'=>'0385503954'); 
// define path to server application 
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter'; 
//define method namespace 
$namespace="urn:xmethods-BNPriceCheck"; 
// create client object 
$client = new soapclient($serverpath); 
// make the call 
$price = $client->call('getPrice',$param,$namespace); 
// if a fault occurred, output error info 
if (isset($fault)) { 
     print "Error: ". $fault; 
     } 
else if ($price == -1) { 
     print "The book is not in the database."; 
} else { 
     // otherwise output the result 
     print "The price of book number ". $param[isbn] ." is $". $price; 
     } 
// kill object 
unset($client); 
?> 
35

En mi experiencia, no es tan sencillo. El PHP SOAP client incorporado no funcionaba con el servidor SOAP basado en .NET que teníamos que usar. Se quejó de una definición de esquema inválida. Aunque el cliente .NET trabajó con ese servidor muy bien. Por cierto, permítanme decir que la interoperabilidad SOAP es un mito.

El siguiente paso fue NuSOAP. Esto funcionó por bastante tiempo. Por cierto, ¡por el amor de Dios, no te olvides de almacenar en caché WSDL! Pero incluso con los usuarios en caché WSDL se quejó de que el maldito asunto es lento.

Entonces, decidimos ir HTTP al descubierto, el montaje de las solicitudes y la lectura de las respuestas con SimpleXMLElemnt, así:

$request_info = array(); 

$full_response = @http_post_data(
    'http://example.com/OTA_WS.asmx', 
    $REQUEST_BODY, 
    array(
     'headers' => array(
      'Content-Type' => 'text/xml; charset=UTF-8', 
      'SOAPAction' => 'HotelAvail', 
     ), 
     'timeout' => 60, 

    ), 
    $request_info 
); 

$response_xml = new SimpleXMLElement(strstr($full_response, '<?xml')); 

foreach ($response_xml->xpath('//@HotelName') as $HotelName) { 
    echo strval($HotelName) . "\n"; 
} 

Tenga en cuenta que en PHP 5.2 que necesita pecl_http, por lo que (sorpresa- surpise!) no hay un cliente HTTP incorporado.

Ir al descubierto HTTP nos ganó más del 30% en los tiempos de solicitud de SOAP. Y a partir de ese momento redirigimos todas las quejas de rendimiento al servidor chicos.

Al final, recomendaría este último enfoque, y no por el rendimiento. Creo que, en general, en un lenguaje dinámico como PHP hay sin beneficio de todo ese WSDL/type-control. No necesita una biblioteca sofisticada para leer y escribir XML, con toda esa generación de stubs y proxies dinámicos. Su idioma ya es dinámico, y SimpleXMLElement funciona bien y es muy fácil de usar. Además, tendrá código menos, que siempre es bueno.

24

PHP tiene soporte SOAP. Sólo tiene que llamar

$client = new SoapClient($url); 

para conectarse a la SoapServer y entonces se puede obtener la lista de funciones y las funciones de llamada simplemente haciendo ...

$client->__getTypes();  
$client->__getFunctions(); 

$result = $client->functionName(); 

para más http://www.php.net/manual/en/soapclient.soapclient.php

+0

¿Es '$ url' la URL del archivo WSDL? – HartleySan

7

que tenía que hacer muchas solicitudes XML muy simples y después de leer el comentario de @Ivan Krechetov sobre el golpe de velocidad de SOAP, probé su código y descubrí que http_post_data() no está integrado en PHP 5.2. No queriendo realmente instalarlo, probé cURL que está en todos mis servidores. Aunque no sé qué tan rápido se compara el cURL con el SOAP, era fácil hacer lo que necesitaba. A continuación se muestra una muestra con cURL para cualquier persona que lo necesite.

$xml_data = '<?xml version="1.0" encoding="UTF-8" ?> 
<priceRequest><customerNo>123</customerNo><password>abc</password><skuList><SKU>99999</SKU><lineNumber>1</lineNumber></skuList></priceRequest>'; 
$URL = "https://test.testserver.com/PriceAvailability"; 

$ch = curl_init($URL); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 
curl_close($ch); 


print_r($output); 
2

A continuación se muestra un ejemplo rápido de cómo hacer esto (que explican mejor el asunto a mí) que, básicamente, he encontrado en this website. El enlace del sitio web también explica WSDL, que es importante para trabajar con servicios SOAP.

Sin embargo, no creo que la dirección de la API que estaban usando en el siguiente ejemplo todavía funcione, así que simplemente cambie la que elija.

$wsdl = 'http://terraservice.net/TerraService.asmx?WSDL'; 

$trace = true; 
$exceptions = false; 

$xml_array['placeName'] = 'Pomona'; 
$xml_array['MaxItems'] = 3; 
$xml_array['imagePresence'] = true; 

$client = new SoapClient($wsdl, array('trace' => $trace, 'exceptions' => $exceptions)); 
$response = $client->GetPlaceList($xml_array); 

var_dump($response); 
2

Podemos utilizar la biblioteca PHP cURL para generar una solicitud HTTP POST simple. El siguiente ejemplo muestra cómo crear una solicitud SOAP simple usando cURL.

Crea el soap-server.php que escribe la solicitud SOAP en soap-request.xml en la carpeta web.

We can use the PHP cURL library to generate simple HTTP POST request. The following example shows you how to create a simple SOAP request using cURL. 

Create the soap-server.php which write the SOAP request into soap-request.xml in web folder. 


<?php 
    $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ''; 
    $f = fopen("./soap-request.xml", "w"); 
    fwrite($f, $HTTP_RAW_POST_DATA); 
    fclose($f); 
?> 


The next step is creating the soap-client.php which generate the SOAP request using the cURL library and send it to the soap-server.php URL. 

<?php 
    $soap_request = "<?xml version=\"1.0\"?>\n"; 
    $soap_request .= "<soap:Envelope xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">\n"; 
    $soap_request .= " <soap:Body xmlns:m=\"http://www.example.org/stock\">\n"; 
    $soap_request .= " <m:GetStockPrice>\n"; 
    $soap_request .= "  <m:StockName>IBM</m:StockName>\n"; 
    $soap_request .= " </m:GetStockPrice>\n"; 
    $soap_request .= " </soap:Body>\n"; 
    $soap_request .= "</soap:Envelope>"; 

    $header = array(
    "Content-type: text/xml;charset=\"utf-8\"", 
    "Accept: text/xml", 
    "Cache-Control: no-cache", 
    "Pragma: no-cache", 
    "SOAPAction: \"run\"", 
    "Content-length: ".strlen($soap_request), 
); 

    $soap_do = curl_init(); 
    curl_setopt($soap_do, CURLOPT_URL, "http://localhost/php-soap-curl/soap-server.php"); 
    curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 10); 
    curl_setopt($soap_do, CURLOPT_TIMEOUT,  10); 
    curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false); 
    curl_setopt($soap_do, CURLOPT_POST,   true); 
    curl_setopt($soap_do, CURLOPT_POSTFIELDS,  $soap_request); 
    curl_setopt($soap_do, CURLOPT_HTTPHEADER,  $header); 

    if(curl_exec($soap_do) === false) { 
    $err = 'Curl error: ' . curl_error($soap_do); 
    curl_close($soap_do); 
    print $err; 
    } else { 
    curl_close($soap_do); 
    print 'Operation completed without any errors'; 
    } 
?> 


Enter the soap-client.php URL in browser to send the SOAP message. If success, Operation completed without any errors will be shown and the soap-request.xml will be created. 

<?xml version="1.0"?> 
<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> 
    <soap:Body xmlns:m="http://www.example.org/stock"> 
    <m:GetStockPrice> 
     <m:StockName>IBM</m:StockName> 
    </m:GetStockPrice> 
    </soap:Body> 
</soap:Envelope> 


Original - http://eureka.ykyuen.info/2011/05/05/php-send-a-soap-request-by-curl/