How to use soap class in php (with example)?

后端 未结 1 1183
广开言路
广开言路 2020-12-04 10:37

I would like to learn the basic usage of SOAP through this (weather) example. How is it worthy to process this data?

Request:

POST /globalweather.asm         


        
相关标签:
1条回答
  • 2020-12-04 11:07

    The most simple approach would be:

    $requestParams = array(
        'CityName' => 'Berlin',
        'CountryName' => 'Germany'
    );
    
    $client = new SoapClient('http://www.webservicex.net/globalweather.asmx?WSDL');
    $response = $client->GetWeather($requestParams);
    
    print_r($response);
    

    would output

    stdClass Object
    (
        [GetWeatherResult] => <?xml version="1.0" encoding="utf-16"?>
    <CurrentWeather>
      <Location>Berlin-Tegel, Germany (EDDT) 52-34N 013-19E 37M</Location>
      <Time>Jan 26, 2012 - 07:50 AM EST / 2012.01.26 1250 UTC</Time>
      <Wind> from the SE (130 degrees) at 14 MPH (12 KT):0</Wind>
      <Visibility> greater than 7 mile(s):0</Visibility>
      <SkyConditions> mostly clear</SkyConditions>
      <Temperature> 33 F (1 C)</Temperature>
      <Wind>Windchill: 23 F (-5 C):1</Wind>
      <DewPoint> 21 F (-6 C)</DewPoint>
      <RelativeHumidity> 59%</RelativeHumidity>
      <Pressure> 30.27 in. Hg (1025 hPa)</Pressure>
      <Status>Success</Status>
    </CurrentWeather>
    )
    

    The rest can then be parsed with SimpleXML or something similar.

    Note, that the kind of response is specific to this web service. There are better web services out there, which do not simply return an xml string, but rather provide the response structure within the WSDL.


    EDIT An example for a "more structured" webservice could be the GeoIP lookup on the same site:

    $client = new SoapClient('http://www.webservicex.net/geoipservice.asmx?WSDL');
    $result = $client->GetGeoIP(array('IPAddress' => '8.8.8.8'));
    
    print_r($result);
    

    this gives you:

    stdClass Object
    (
        [GetGeoIPResult] => stdClass Object
            (
                [ReturnCode] => 1
                [IP] => 8.8.8.8
                [ReturnCodeDetails] => Success
                [CountryName] => United States
                [CountryCode] => USA
            )
    
    )
    

    Now you can simply access the values by invoking

    $country = $result->GetGeoIPResult->CountryName;
    
    0 讨论(0)
提交回复
热议问题