问题
As SOAP client returns XML response by default, I need to get JSON response in return instead of XML.
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
'uri' => "http://test-uri/"));
In that case what attribute needs to be set in SOAPClient or SOAPHeader so that it returns JSON response?
回答1:
From what I have been able to find out from some research, the SoapClient does not have any built in way to return the data directly as JSON (anyone else know if I'm wrong, it would save a heck of a lot of processing after the fact!) so you will probably need to take the XML returned data and parse it out manually.
I recalled that SimpleXMLElement offers some useful features, and sure enough, someone had some code snippets on php.net to do exactly that: 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);
}
?>
回答2:
SOAP supports only XML message format.
If the SOAP server you are trying to connect is a third party one to which you do not have direct access, you will have to convert the XML response to JSON after receiving, like this example here
If you want your web service server to support different data types like json, you need to look into RESTful web services.
回答3:
If your result is in PHP Array format, for example :
object(stdClass)#2 (6) { ["category_id"]=> int(1) ["parent_id"]=> int(0) ["name"]=> string(12) "Root Catalog" ["position"]=> int(0)..........
Then you can parse it to JSON using,
//result is the variable with php array value
$JSON = json_encode($result);
print_r($JSON);
For detailed understanding, watch - https://www.youtube.com/watch?v=isuXO5Cv6Lg
来源:https://stackoverflow.com/questions/13245008/how-to-get-json-response-from-soap-call-in-php