由于 SOAP 客户端默认返回 XML 响应,因此我需要获取 JSON 响应而不是 XML。
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
'uri' => "http://test-uri/"));
Run Code Online (Sandbox Code Playgroud)
在这种情况下,需要在SOAPClient或SOAPHeader 中设置什么属性才能返回 JSON 响应?
根据我从一些研究中发现的信息,SoapClient 没有任何内置方式将数据直接作为 JSON 返回(如果我错了,其他人都知道,它会在事实!)所以您可能需要获取 XML 返回的数据并手动解析它。
我记得 SimpleXMLElement 提供了一些有用的功能,果然,有人在php.net上有一些代码片段来做到这一点:http : //php.net/manual/en/class.simplexmlelement.php
<?php
function XML2JSON($xml) {
function normalizeSimpleXML($obj, &$result) {
$data = $obj;
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
foreach ($data as $key => $value) {
$res = null;
normalizeSimpleXML($value, $res);
if (($key == '@attributes') && ($key)) {
$result = $res;
} else {
$result[$key] = $res;
}
}
} else {
$result = $data;
}
}
normalizeSimpleXML(simplexml_load_string($xml), $result);
return json_encode($result);
}
?>
Run Code Online (Sandbox Code Playgroud)