【php】SOAPする
問題
SOAPでとあるシステムとやり取りすることになりました。phpでどうやったらよい?

答え
1、情報を確認
とりあえずリクエスト先URLを知りたい
例)https://soap.example.jp/soap/NamedResourceService
2、WSDL確認
SOAPの場合WSDLが提供される。URLが不明だったら ~?wsdl を付けてみるとよい。
例)https://soap.example.jp/soap/NamedResourceService?wsdl
3、phpを書く
phpのSOAPを使うとこんな感じ。
<?php
$client = new SoapClient('https://soap.example.jp/soap/NamedResourceService?wsdl');
//wsdlの内容が変でリクエスト先をあえて指定しないといけない場合
//$client->__setLocation('https://soap.example.jp/soap/NamedResourceService');
$response = $client->呼びたいメソッド名(
new SoapParam($hoge, "パラメータ名1"),
new SoapParam($fuga, "パラメータ名2"),
new SoapParam($piyo, "パラメータ名3")
);
以下のようにすると、文字列として引数を作ってくれるのだが、
new SoapParam($hoge, "パラメータ名")
型を指定したいときはSoapVarで。
$_hoge= 'ごにょごにょ'; $hoge = new SoapVar($_hoge, XSD_STRING, "string", "http://www.w3.org/2001/XMLSchema"); $response = $client->hogeService(new SoapParam($hoge, "パラメータ名1"));
phpのSOAPクライアントに依存しない場合
SOAPのリクエストって、要するにXMLを作ってPOSTなりすればよいので、file_get_contents()でも呼べる。
自力でXMLを作り、自力でリクエストを送信する場合、リクエストのデータの手作りで何らかの問題にはまるかもしれない。生のレスポンスを取得してしまうので、レスポンスの処理が少しだけ手間かもしれない。でも、依存するものが少ないのがメリット。
<?php
$data = '<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://xxxx" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:hogeService><hogeParam xsi:type="xsd:string">パラメータ1</hogeParam></ns1:hogeService></SOAP-ENV:Body></SOAP-ENV:Envelope>';
$options = array(
'http'=>array(
'method' => 'POST',
'header' => "Content-type: application/soap+xml; charset=UTF-8\r\n"
. "Content-Length: " . strlen($data) . "\r\n"
. 'SOAPAction: ""',
'content' => $data
)
);
$context = stream_context_create($options);
$response = file_get_contents('https://soap.example.jp/soap/NamedResourceService', false, $context);