Consume WebService with php

php, web-services

Solution

Here's a simple example which uses curl and the GET interface.

$zip = 97219;
$url = "http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip=$zip";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($ch);

curl_close($ch);

$xmlobj = simplexml_load_string($result);

The `$result` variable contains XML which looks like this

<?xml version="1.0" encoding="utf-8"?>
<NewDataSet>
  <Table>
    <CITY>Portland</CITY>
    <STATE>OR</STATE>
    <ZIP>97219</ZIP>
    <AREA_CODE>503</AREA_CODE>
    <TIME_ZONE>P</TIME_ZONE>
  </Table>
</NewDataSet>

Once the XML is parsed into a SimpleXML object, you can get at the various nodes like this:

print $xmlobj->Table->CITY;

If you want to get fancy, you could throw the whole thing into a class:

class GetInfoByZIP {
    public $zip;
    public $xmlobj;

    public function __construct($zip='') {
        if($zip) {
            $this->zip = $zip;
            $this->load();
        }
    }

    public function load() {
        if($this->zip) {
            $url = "http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip={$this->zip}";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            $result = curl_exec($ch);

            curl_close($ch);

            $this->xmlobj = simplexml_load_string($result);
        }
    }

    public function __get($name) {
        return $this->xmlobj->Table->$name;
    }
}

which can then be used like this:

$zipInfo = new GetInfoByZIP(97219);

print $zipInfo->CITY;

Problem

Can anyone give me an example of how I can consume the following web service with php? http://www.webservicex.net/uszip.asmx?op=GetInfoByZIP

Original source