簡體   English   中英

用php來使用WebService

[英]Consume WebService with php

任何人都可以給我一個例子,說明如何使用php來使用以下Web服務?

http://www.webservicex.net/uszip.asmx?op=GetInfoByZIP

這是一個使用curl和GET接口的簡單示例。

$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);

$result變量包含看起來像這樣的XML

<?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>

將XML解析為SimpleXML對象后,您可以獲得如下所示的各種節點:

print $xmlobj->Table->CITY;

如果你想獲得幻想,你可以把整個事情扔進一個類:

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;
    }
}

然后可以像這樣使用:

$zipInfo = new GetInfoByZIP(97219);

print $zipInfo->CITY;

我會使用curl的HTTP POST或GET接口。 看起來它為您提供了一個很好的干凈XML輸出,您可以使用simpleXML進行解析。

像下面這樣的東西會一路走來(警告,完全未經測試):

$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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM