【问题标题】:Loop through result from a .NET web service call in php循环通过 php 中的 .NET Web 服务调用的结果
【发布时间】:2012-04-02 06:40:37
【问题描述】:

我正在使用一种返回通用列表的方法从 .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 网络服务代码

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 网络服务的 php 代码

$client = new SoapClient("http://testURL/MyTestService.asmx?WSDL");

$params->Param1 = 'Hello'; 
$params->Param2 = 'World!';

$result = $client->testAspMethod($params)->testAspMethodResult;

var_dump($result);

如何在 php 中循环遍历结果?

【问题讨论】:

    标签: php asp.net web-services wsdl


    【解决方案1】:

    无论返回的项目数量如何,这都会起作用。如果你不像我在这里那样做数组检查,你的代码会产生意想不到的结果。如果 web 服务只返回一个项目,它不会返回一个数组。相反,它实际上会将对象直接放在$result-&gt;testClass 中,例如$result-&gt;testClass-&gt;City 不是您所期望的 $result-&gt;testClass[0]-&gt;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 />';
    }
    

    【讨论】:

      【解决方案2】:

      如果您知道返回的名称(在本例中为 testClass),您可以...

      foreach($result->testClass as $key => $obj){
          echo "Key: $key\n";
          echo $obj->City . "\n";
          echo $obj->State . "\n";
      }
      

      【讨论】:

      • 不幸的是,如果 web 服务返回单个对象而不是多个对象,这将不起作用。
      猜你喜欢
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多