WordPress教程

WordPress中使用wp_remote_post调用SOAP接口的数据

阿里云

相对于 REST API, SOAP 是一种比较复杂的 Web Service 接口,理论上,我们可以使用 PHP 的 SoapClient 类来访问 SOAP 接口获取数据。

在开发一个 WordPress 主题的时候,我们尝试过使用这个类来访问一下用户同步的 API,可经过多次尝试,都不能成功,遂放弃,尝试使用 WordPress 的 wp_remote_post 函数来访问这个接口,很快成功了。

也想出现在这里?联系我们
创客主机

准备需要发送的 SOAP 接口的数据

根据 SOAP 接口文档,我们先准备好需要发送到 SOAP 的数据,如下,这些数据是一个标准的 PHP 数组。每个 SOAP 接口需要的数据不一样,下面的数据只是示例,具体使用的时候,请根据自己的需要准备这些数据。

  1. $params = [
  2.     'data' => [
  3.         'header' => [
  4.             'security'   => [],
  5.             'time'       => '2017-12-06',
  6.             'sender'     => 'user1',
  7.             'where'      => "time between '2020-07-25 00:00:00' and '2020-07-30 13:59:03'",
  8.         ],
  9.     ],
  10. ];

转换后的,需要实际发送的 SOAP 接口的 XML 数据,由于 SOAP 使用的是 XML 格式的数据,在发送数据之前,我们需要先把上面的数组转化成 XML 格式。

  1. $xml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:izn="http://example.com/service">
  2.    <soapenv:Header/>
  3.    <soapenv:Body>
  4.       <izn:doQuery>
  5.          <string>' . json_encode($params) . '</string>
  6.       </izn:doQuery>
  7.    </soapenv:Body>
  8. </soapenv:Envelope>';

使用 wp_remote_post 函数发送数据到 SOAP 的主要代码

转换之后,我们需要把这个 XML 数据作为 HTTP 的 body 信息发送给 SOAP,同时需要设置一下 HTTP Header,说明我们需要传输的数据是 xml,并设置内容长度和超时时间。

  1. $service_url = 'http://example.php/service';
  2.  
  3. $headers = [
  4.     'Content-Type'   => 'text/xml',
  5.     'Content-Length' => strlen($xml),
  6.     'timeout'        => 600,
  7. ];
  8.  
  9. $response = wp_remote_post($service_url, [
  10.     'headers' => $headers,
  11.     'body'    => $xml,
  12. ]);

从 SOAP 获取的数据格式也是 XML 格式的,我们根据需要转换成 PHP 对象或数组来使用就可以了。

使用 PHP cURL 库获取 SOAP 数据

本质上,WordPress 的 wp_remote_post 函数是通过 PHP 的 cURL 库请求网络的,所以我们也可以直接使用 cURL 来请求 SOAP 接口获取数据。

  1. $ch = curl_init();
  2. curl_setopt($ch, CURLOPT_URL, $service_url);
  3. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  4. curl_setopt($ch, CURLOPT_TIMEOUT, 1000);
  5. curl_setopt($ch, CURLOPT_POST, true);
  6. curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); // the SOAP request
  7.  
  8. // converting
  9. $response = curl_exec($ch);
  10. curl_close($ch);

根据我们的经验,SOAP 相对于 REST API,使用起来相当麻烦,如果是构建自己的 API,建议优先使用 REST API,对节省不少时间。

WordPress 中使用 wp_remote_post 调用 SOAP 接口的数据

已有 203 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!