Web服务-如何从PHP发布SOAP请求

有人知道如何从PHP发布SOAP请求吗?

Jin Yong asked 2020-02-13T11:49:44Z
7个解决方案
44 votes

以我的经验,这并不是那么简单。 内置的PHP SOAP客户端无法与我们不得不使用的基于.NET的SOAP服务器一起使用。 它抱怨模式定义无效。 即使.NET客户端可以与该服务器正常工作。 顺便说一下,让我声称SOAP互操作性是一个神话。

下一步是NuSOAP。 这工作了一段时间。 顺便说一下,看在上帝的份上,不要忘记缓存WSDL! 但是即使使用WSDL缓存的用户也抱怨该死的东西很慢。

然后,我们决定采用裸HTTP,组装请求并使用SimpleXMLElement读取响应,如下所示:

$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";
}

请注意,在PHP 5.2中,您需要pecl_http,因为(surprise-surpise!)没有内置的HTTP客户端。

裸露的HTTP使我们的SOAP请求时间超过了30%。 从那时起,我们将所有性能投诉重定向到服务器人员。

最后,我建议使用后一种方法,而不是因为性能。 我认为,一般而言,在像PHP这样的动态语言中,WSDL /类型控制无法带来任何好处。 您不需要花哨的库就可以读取和写入XML,并且具有所有存根生成和动态代理。 您的语言已经是动态的,SimpleXMLElement可以正常工作,并且易于使用。 另外,您将拥有更少的代码,这总是很好。

Ivan Krechetov answered 2020-02-13T11:50:17Z
27 votes

PHP具有SOAP支持。刚打电话

$client = new SoapClient($url);

连接到SoapServer,然后只需执行以下操作即可获取函数列表和调用函数:

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

$result = $client->functionName();  

有关更多信息[http://www.php.net/manual/zh/soapclient.soapclient.php]

Sharj answered 2020-02-13T11:50:46Z
8 votes

我需要执行许多非常简单的XML请求,并且在阅读@Ivan Krechetov关于SOAP带来的速度问题的评论后,我尝试了他的代码,发现PHP 5.2中没有内置http_post_data()。 我并不是真的想要安装它,而是尝试了所有服务器上的cURL。 尽管我不知道cURL与SOAP相比有多快,但是确实可以轻松完成我需要的操作。 以下是需要cURL的示例。

$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);
Tim Duncklee answered 2020-02-13T11:51:07Z
5 votes

我们可以使用PHP cURL库生成简单的HTTP POST请求。 以下示例显示了如何使用cURL创建简单的SOAP请求。

创建soap-server.php,它将SOAP请求写入Web文件夹中的soap-request.xml中。

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/
senanqerib answered 2020-02-13T11:51:31Z
3 votes

您可能想在这里和这里看看。

第一个链接中的Little代码示例:

<?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);
?>
Filip Ekberg answered 2020-02-13T11:51:56Z
2 votes

以下是我在此网站上发现的快速操作示例(最能向我解释此事)。 该网站链接还解释了WSDL,这对于使用SOAP服务很重要。

但是,我认为他们在下面的示例中使用的API地址仍然无效,因此只需切换一个即可。

$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);
Cato Minor answered 2020-02-13T11:52:22Z
1 votes

如果XML在不同级别具有相同名称的标识,则有解决方案。 您不必提交原始XML(此PHP SOAP对象不允许发送RAW XML),因此您必须始终将XML转换为数组,如以下示例所示:

$originalXML = "
<xml>
  <firstClient>
      <name>someone</name>
      <adress>R. 1001</adress>
  </firstClient>
  <secondClient>
      <name>another one</name>
      <adress></adress>
  </secondClient>
</xml>"

//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' => ''));

$webService = new SoapClient($someURL);
$result = $webService->someWebServiceFunction($myParams);

要么

$soapUrl = "http://privpakservices.schenker.nu/package/package_1.3/packageservices.asmx?op=SearchCollectionPoint";

$xml_post_string = '<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"><soap12:Body><SearchCollectionPoint xmlns="http://privpakservices.schenker.nu/"><customerID>XXX</customerID><key>XXXXXX-XXXXXX</key><serviceID></serviceID><paramID>0</paramID><address>RiksvŠgen 5</address><postcode>59018</postcode><city>Mantorp</city><maxhits>10</maxhits></SearchCollectionPoint></soap12:Body></soap12:Envelope>';

$headers = array(
"POST /package/package_1.3/packageservices.asmx HTTP/1.1",
"Host: privpakservices.schenker.nu",
"Content-Type: application/soap+xml; charset=utf-8",
"Content-Length: ".strlen($xml_post_string)
); 

$url = $soapUrl;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch); 
curl_close($ch);

$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);

$parser = simplexml_load_string($response2);
Saber Daagi answered 2020-02-13T11:52:46Z
translate from https://stackoverflow.com:/questions/471115/how-to-post-soap-request-from-php