我正在使用一个返回泛型列表的方法从.net web服务中获取结果。在php页面中使用var_dump(它使用WSDL调用.net方法),我能够看到从.net web服务返回的以下内容:
object(stdClass)#4 (1) {
["testClass"]=> array(2) {
[0]=> object(stdClass)#5 (2) {
["City"]=> string(7) "Hello_1"
["State"]=> string(8) "World!_1"
}
[1]=> object(stdClass)#6 (2) {
["City"]=> string(7) "Hello_2"
["State"]=> string(8) "World!_2"
}
}
}
这可能是一个愚蠢的问题,但我一直在php中处理(循环)这个结果?我是否也必须在php中创建类"testClass"?
这是.net Web服务代码
public class testClass
{
public string City;
public string State;
}
[WebMethod]
public List<testClass> testAspMethod(string Param1, string Param2)
{
List<testClass> l = new List<testClass>();
l.Add(new testClass { City = Param1 + "_1", State = Param2 + "_1" });
l.Add(new testClass { City = Param1 + "_2", State = Param2 + "_2" });
return l;
}
以下是调用这个.net web服务的php代码
$client=新SoapClient("http://testURL/MyTestService.asmx?WSDL");
$params->Param1 = 'Hello';
$params->Param2 = 'World!';
$result = $client->testAspMethod($params)->testAspMethodResult;
var_dump($result);
如何在php中循环显示结果?
无论返回的项目数量如何,这都会起作用。如果你不像我在这里做的那样进行数组检查,你的代码会产生意想不到的结果。如果webservice只返回一个项,则不会返回数组。相反,它实际上会将对象直接放在$result->testClass
中,例如$result->testClass->City
,而不是您所期望的$result->testClass[0]->City
。
// here we make sure we have an array, even if there's just one item in it
if(is_array($result->testClass))
{
$result = $result->testClass;
}
else
{
$result = array($result->testClass);
}
foreach($result as $item)
{
echo 'City: ' . $item->City . '<br />';
echo 'State: ' . $item->State . '<br />';
}
如果您知道返回的名称(在本例中为testClass),您可以。。。
foreach($result->testClass as $key => $obj){
echo "Key: $key'n";
echo $obj->City . "'n";
echo $obj->State . "'n";
}