简体   繁体   中英

How to access returned object from SOAP webservice using PHP

I am trying to consume a SOAP based webservice uisng PHP. Following is the sample code. I need to know/learn how to access the retur'ed object elements? Please note i am new to 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

Can anyone please help me how to access this object in PHP and why?

First of all, u're using $CITY variable to access $result property and you haven't defined it yet.

So if you want to get "CITY" property inside "result" object you should do it by "$result->City".

According to result you get - it's a xml string, not object. If you want to access string do it this way:

$result->GetInfoByZIPResult->any

You can load string with DomDocument or simplexml lib.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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