如何使用PHP访问SOAP web服务返回的对象


How to access returned object from SOAP webservice using PHP

我正在尝试使用PHP使用基于SOAP的web服务。下面是示例代码。我需要知道/学习如何访问返回的对象元素?请注意我是PHP新手

    $url = 'http://www.webservicex.net/uszip.asmx?WSDL';
    $soap = new SoapClient($url, array(
        "trace"      => 1,      // enable trace to view what is happening
        "exceptions" => 0,      // disable exceptions
        "cache_wsdl" => 0) );
    try {
        $result = $soap->GetInfoByZIP(array('USZip' => '97219'));
        echo($result->$CITY);
        //print_r( $soap->GetInfoByZIP(array("USZip" => "97219")));
    } catch (SoapFault $e) {
        echo "Error: {$e->faultstring}";
    }

得到以下异常

Notice: Undefined variable: CITY 
Fatal error: Cannot access empty property 

但是,当我执行上面的注释行时,它返回以下响应

 stdClass Object
(
    [GetInfoByZIPResult] => stdClass Object
        (
            [any] => <NewDataSet xmlns=""><Table><CITY>Portland</CITY><STATE>OR</STATE><ZIP>97219</ZIP><AREA_CODE>503</AREA_CODE><TIME_ZONE>P</TIME_ZONE></Table></NewDataSet>
        )
)

这意味着数据正在返回,但我不能像。net

那样访问它

谁能帮我如何访问这个对象在PHP和为什么?

首先,您使用$CITY变量来访问$result属性,并且您还没有定义它。

所以如果你想在"result"对象中获得"CITY"属性,你应该通过"$result-> CITY"来实现。

根据你得到的结果-它是一个xml字符串,而不是对象。如果你想访问字符串,这样做:

$result->GetInfoByZIPResult->any

您可以使用DomDocument或simplexml库加载字符串