使用PHP使用WebService [英] Consume WebService with php

查看:107
本文介绍了使用PHP使用WebService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以给我一个如何使用php来使用以下Web服务的示例吗?

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

推荐答案

这是一个使用curl和GET接口的简单示例.

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

$result变量包含如下所示的XML

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>

一旦将XML解析为SimpleXML对象,您就可以像这样到达各个节点:

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

然后可以像这样使用:

$zipInfo = new GetInfoByZIP(97219);

print $zipInfo->CITY;

这篇关于使用PHP使用WebService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆