PHP 코드 작성에 익숙하지만 종종 객체 지향 코딩을 사용하지 않습니다. 이제 SOAP (클라이언트)와 상호 작용해야하며 구문을 제대로 얻을 수 없습니다. SoapClient 클래스를 사용하여 새 연결을 올바르게 설정할 수있는 WSDL 파일이 있습니다. 그러나 실제로 올바른 전화를 걸고 데이터를 가져올 수는 없습니다. 다음 (간체 화 된) 데이터를 보내야합니다.
- 연락 ID
- 담당자 이름
- 일반적인 설명
- 양
WSDL 문서에는 두 개의 함수가 정의되어 있지만 하나만 필요합니다 (아래 “FirstFunction”). 사용 가능한 기능 및 유형에 대한 정보를 얻기 위해 실행하는 스크립트는 다음과 같습니다.
$client = new SoapClient("http://example.com/webservices?wsdl");
var_dump($client->__getFunctions());
var_dump($client->__getTypes());
그리고 여기에 생성되는 출력이 있습니다 :
array(
[0] => "FirstFunction Function1(FirstFunction $parameters)",
[1] => "SecondFunction Function2(SecondFunction $parameters)",
);
array(
[0] => struct Contact {
id id;
name name;
}
[1] => string "string description"
[2] => string "int amount"
}
데이터로 FirstFunction을 호출하고 싶다고 가정 해보십시오.
- 연락 ID : 100
- 담당자 이름 : John
- 일반 설명 : 오일 배럴
- 금액 : 500
올바른 구문은 무엇입니까? 나는 모든 종류의 옵션을 시도했지만 비누 구조가 상당히 유연 해 보이기 때문에 많은 방법이 있습니다. 매뉴얼에서도 알아낼 수 없었습니다 …
업데이트 1 : MMK에서 시도한 샘플 :
$client = new SoapClient("http://example.com/webservices?wsdl");
$params = array(
"id" => 100,
"name" => "John",
"description" => "Barrel of Oil",
"amount" => 500,
);
$response = $client->__soapCall("Function1", array($params));
그러나 나는이 응답을 얻는다 : Object has no 'Contact' property
. 당신의 출력에서 볼 수 있듯이 getTypes()
, 거기입니다 struct
라는 Contact
내가 어떻게 든 내 매개 변수는 연락처 데이터를 포함 취소해야 같아요, 그래서,하지만 질문은 : 어떻게?
업데이트 2 :이 구조를 시도했지만 동일한 오류가 발생했습니다.
$params = array(
array(
"id" => 100,
"name" => "John",
),
"Barrel of Oil",
500,
);
만큼 잘:
$params = array(
"Contact" => array(
"id" => 100,
"name" => "John",
),
"description" => "Barrel of Oil",
"amount" => 500,
);
두 경우 모두 오류 : 개체에 ‘연락처’속성이 없습니다`
답변
이것이 당신이해야 할 일입니다.
상황을 재현하려고했습니다 …
- 이 예를 들어, 나는이와 .NET 샘플 WebService에 (WS) 창조
WebMethod
라는Function1
다음 PARAMS 기대를 :
Function1 (연락처, 문자열 설명, int 금액)
-
귀하의 경우 와 마찬가지로
Contact
getter 및 setter가있는 모델은 어디에 있습니까 ?id
name
-
다음에서 .NET 샘플 WS를 다운로드 할 수 있습니다.
https://www.dropbox.com/s/6pz1w94a52o5xah/11593623.zip
코드.
이것은 PHP 측에서해야 할 일입니다.
(테스트 및 작동)
<?php
// Create Contact class
class Contact {
public function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
}
// Initialize WS with the WSDL
$client = new SoapClient("http://localhost:10139/Service1.asmx?wsdl");
// Create Contact obj
$contact = new Contact(100, "John");
// Set request params
$params = array(
"Contact" => $contact,
"description" => "Barrel of Oil",
"amount" => 500,
);
// Invoke WS method (Function1) with the request params
$response = $client->__soapCall("Function1", array($params));
// Print WS response
var_dump($response);
?>
모든 것을 테스트합니다.
- 당신이 경우에
print_r($params)
당신의 WS가 기대하는 것처럼 당신은 다음과 같은 출력이 표시됩니다 :
배열 ([Contact] => Contact Object ([id] => 100 [name] => John) [description] => 오일 배럴 [amount] => 500)
- .NET 샘플 WS를 디버깅 할 때 다음을 얻었습니다.
(보시다시피, Contact
객체 null
도 다른 매개 변수도 아닙니다. 요청이 PHP 측에서 성공적으로 완료되었음을 의미합니다)
- .NET 샘플 WS의 응답은 예상 한 것이며 PHP 측에서 얻은 것입니다.
object (stdClass) [3] public ‘Function1Result’=> string ‘요청에 대한 자세한 정보! id : 100, 이름 : John, 설명 : 오일 배럴, 양 : 500 ‘(길이 = 98)
행복한 코딩!
답변
이 방법으로 SOAP 서비스를 사용할 수도 있습니다.
<?php
//Create the client object
$soapclient = new SoapClient('http://www.webservicex.net/globalweather.asmx?WSDL');
//Use the functions of the client, the params of the function are in
//the associative array
$params = array('CountryName' => 'Spain', 'CityName' => 'Alicante');
$response = $soapclient->getWeather($params);
var_dump($response);
// Get the Cities By Country
$param = array('CountryName' => 'Spain');
$response = $soapclient->getCitiesByCountry($param);
var_dump($response);
이것은 실제 서비스의 예이며 작동합니다.
도움이 되었기를 바랍니다.
답변
먼저 웹 서비스를 초기화하십시오.
$client = new SoapClient("http://example.com/webservices?wsdl");
그런 다음 매개 변수를 설정하고 전달하십시오.
$params = array (
"arg0" => $contactid,
"arg1" => $desc,
"arg2" => $contactname
);
$response = $client->__soapCall('methodname', array($params));
메소드 이름은 WSDL에서 조작 이름으로 사용 가능합니다. 예를 들면 다음과 같습니다.
<operation name="methodname">
답변
내 웹 서비스의 구조가 왜 같은지 모르겠지만 매개 변수에 클래스가 필요하지 않고 배열입니다.
예를 들면 다음과 같습니다.-내 WSDL :
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns="http://www.kiala.com/schemas/psws/1.0">
<soapenv:Header/>
<soapenv:Body>
<ns:createOrder reference="260778">
<identification>
<sender>5390a7006cee11e0ae3e0800200c9a66</sender>
<hash>831f8c1ad25e1dc89cf2d8f23d2af...fa85155f5c67627</hash>
<originator>VITS-STAELENS</originator>
</identification>
<delivery>
<from country="ES" node=””/>
<to country="ES" node="0299"/>
</delivery>
<parcel>
<description>Zoethout thee</description>
<weight>0.100</weight>
<orderNumber>10K24</orderNumber>
<orderDate>2012-12-31</orderDate>
</parcel>
<receiver>
<firstName>Gladys</firstName>
<surname>Roldan de Moras</surname>
<address>
<line1>Calle General Oraá 26</line1>
<line2>(4º izda)</line2>
<postalCode>28006</postalCode>
<city>Madrid</city>
<country>ES</country>
</address>
<email>gverbruggen@kiala.com</email>
<language>es</language>
</receiver>
</ns:createOrder>
</soapenv:Body>
</soapenv:Envelope>
나는 var_dump :
var_dump($client->getFunctions());
var_dump($client->getTypes());
결과는 다음과 같습니다.
array
0 => string 'OrderConfirmation createOrder(OrderRequest $createOrder)' (length=56)
array
0 => string 'struct OrderRequest {
Identification identification;
Delivery delivery;
Parcel parcel;
Receiver receiver;
string reference;
}' (length=130)
1 => string 'struct Identification {
string sender;
string hash;
string originator;
}' (length=75)
2 => string 'struct Delivery {
Node from;
Node to;
}' (length=41)
3 => string 'struct Node {
string country;
string node;
}' (length=46)
4 => string 'struct Parcel {
string description;
decimal weight;
string orderNumber;
date orderDate;
}' (length=93)
5 => string 'struct Receiver {
string firstName;
string surname;
Address address;
string email;
string language;
}' (length=106)
6 => string 'struct Address {
string line1;
string line2;
string postalCode;
string city;
string country;
}' (length=99)
7 => string 'struct OrderConfirmation {
string trackingNumber;
string reference;
}' (length=71)
8 => string 'struct OrderServiceException {
string code;
OrderServiceException faultInfo;
string message;
}' (length=97)
내 코드에서 :
$client = new SoapClient('http://packandship-ws.kiala.com/psws/order?wsdl');
$params = array(
'reference' => $orderId,
'identification' => array(
'sender' => param('kiala', 'sender_id'),
'hash' => hash('sha512', $orderId . param('kiala', 'sender_id') . param('kiala', 'password')),
'originator' => null,
),
'delivery' => array(
'from' => array(
'country' => 'es',
'node' => '',
),
'to' => array(
'country' => 'es',
'node' => '0299'
),
),
'parcel' => array(
'description' => 'Description',
'weight' => 0.200,
'orderNumber' => $orderId,
'orderDate' => date('Y-m-d')
),
'receiver' => array(
'firstName' => 'Customer First Name',
'surname' => 'Customer Sur Name',
'address' => array(
'line1' => 'Line 1 Adress',
'line2' => 'Line 2 Adress',
'postalCode' => 28006,
'city' => 'Madrid',
'country' => 'es',
),
'email' => 'test.ceres@yahoo.com',
'language' => 'es'
)
);
$result = $client->createOrder($params);
var_dump($result);
그러나 성공적으로!
답변
이것을 읽으십시오;-
http://php.net/manual/en/soapclient.call.php
또는
SOAP 함수 “__call”에 대한 좋은 예입니다. 그러나 더 이상 사용되지 않습니다.
<?php
$wsdl = "http://webservices.tekever.eu/ctt/?wsdl";
$int_zona = 5;
$int_peso = 1001;
$cliente = new SoapClient($wsdl);
print "<p>Envio Internacional: ";
$vem = $cliente->__call('CustoEMSInternacional',array($int_zona, $int_peso));
print $vem;
print "</p>";
?>
답변
먼저 SoapUI 를 사용하여 wsdl에서 soap 프로젝트를 작성하십시오. wsdl의 조작에 대한 재생 요청을 보내십시오. xml 요청이 데이터 필드를 구성하는 방법을 관찰하십시오.
그런 다음 SoapClient가 원하는대로 작동하는 데 문제가 있으면 여기에 디버깅 방법이 있습니다. __getLastRequest () 함수 를 사용할 수 있도록 옵션 추적을 설정하십시오 .
$soapClient = new SoapClient('http://yourwdsdlurl.com?wsdl', ['trace' => true]);
$params = ['user' => 'Hey', 'account' => '12345'];
$response = $soapClient->__soapCall('<operation>', $params);
$xml = $soapClient->__getLastRequest();
그런 다음 $ xml 변수에는 SoapClient가 요청을 위해 작성하는 xml이 포함됩니다. 이 xml을 SoapUI에서 생성 된 xml과 비교하십시오.
나를 위해 SoapClient는 연관 배열 $ params 의 키를 무시하고 색인 배열로 해석하여 XML에 잘못된 매개 변수 데이터를 발생시키는 것으로 보입니다 . 즉, $ params 의 데이터를 재정렬 하면 $ response 는 완전히 다릅니다.
$params = ['account' => '12345', 'user' => 'Hey'];
$response = $soapClient->__soapCall('<operation>', $params);
답변
SoapParam의 개체를 만들면 문제가 해결됩니다. 클래스를 작성하고 WebService에서 제공 한 오브젝트 유형으로 맵핑 한 후 값을 초기화하고 요청을 전송하십시오. 아래 샘플을 참조하십시오.
struct Contact {
function Contact ($pid, $pname)
{
id = $pid;
name = $pname;
}
}
$struct = new Contact(100,"John");
$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "Contact","http://soapinterop.org/xsd");
$ContactParam = new SoapParam($soapstruct, "Contact")
$response = $client->Function1($ContactParam);
![](http://daplus.net/wp-content/uploads/2023/04/coupang_part-e1630022808943-2.png)