views:

594

answers:

2

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

+2  A: 

I would use the HTTP POST or GET interfaces with curl. It looks like it gives you a nice clean XML output that you could parse with simpleXML.

Something like the following would go along way (warning, totally untested here):

$ch = curl_init('http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip=string');

curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
$xml = curl_exec($ch);
curl_close($ch);
$parsed = new SimpleXMLElement($xml);

print_r($parsed);
acrosman
i think he is asking about the format, but Cory" read the shown examples
dusoft
+5  A: 

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-&gt;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;
Mark Biek