简体   繁体   English

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

[英]How to access returned object from SOAP webservice using PHP

I am trying to consume a SOAP based webservice uisng PHP. 我正在尝试使用基于ui的PHP SOAP Web服务。 Following is the sample code. 以下是示例代码。 I need to know/learn how to access the retur'ed object elements? 我需要知道/学习如何访问retur'ed对象元素? Please note i am new to PHP 请注意,我是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}";
    }

I get the following exception 我得到以下异常

Notice: Undefined variable: CITY 

Fatal error: Cannot access empty property 

However when I execute the commented line above it return the following response 但是,当我执行上面的注释行时,返回以下响应

 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>
        )

)

So this means that data is being returned but i am not able to access it like the way done in .NET 因此,这意味着将返回数据,但我无法像在.NET中那样访问数据

Can anyone please help me how to access this object in PHP and why? 谁能帮助我如何在PHP中访问此对象,为什么?

First of all, u're using $CITY variable to access $result property and you haven't defined it yet. 首先,您正在使用$ CITY变量来访问$ result属性,但尚未定义它。

So if you want to get "CITY" property inside "result" object you should do it by "$result->City". 因此,如果要在“结果”对象中获取“ CITY”属性,则应通过“ $ result-> City”来实现。

According to result you get - it's a xml string, not object. 根据结果​​,您得到-这是一个xml字符串,而不是对象。 If you want to access string do it this way: 如果要访问字符串,请按照以下方式进行操作:

$result->GetInfoByZIPResult->any

You can load string with DomDocument or simplexml lib. 您可以使用DomDocument或simplexml lib加载字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM