Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

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.

share|improve this answer
 
Thanks for the help! It apparently worked but when i try to print out the object it preints blank :/ but when i print object as XML it shows me the data. Need to know how to reference properties of object now :) Here is the code $obj = simplexml_load_string($result->GetInfoByZIPResult->any); echo $obj->asXML(); –  Salman Ahmad Mar 5 at 17:03
 
If you successfully converted XML string into an object, you can access it's properties as simple as that: $obj->Table->City. And yes - dumping such objects has different behaviour from usuall. –  Maciej Jaśniaczyk Mar 6 at 9:17
 
Let me know if you need any additional help :) –  Maciej Jaśniaczyk Mar 7 at 11:36
 
Great thanks. It helped! –  Salman Ahmad Mar 11 at 15:42
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.