PHP函数从Web服务获取数据 [英] PHP function to get data from web service

查看:117
本文介绍了PHP函数从Web服务获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用PHP从此Web服务中获取数据?

How can I get data from this web service using PHP?

我需要一个简单的PHP函数来列出国家/地区.

I need a simple PHP function to list the countries.

{
   "valid":true,
   "id":"0",
   "data":{
      "@type":"genericObjectArray",
      "item":[
         {
            "id":"DE",
            "description":"Deutschland"
         },
         {
            "id":"ES",
            "description":"España"
         },
         {
            "id":"FR",
            "description":"France"
         },
         {
            "id":"PT",
            "description":"Portugal"
         },
         {
            "id":"UK",
            "description":"United Kingdom"
         },
         {
            "id":"US",
            "description":"United States"
         }
      ]
   }
}

推荐答案

假设 allow_url_fopen 已在php.ini中打开(如果没有,请使用cURL库).

Assuming allow_url_fopen is on in php.ini (if not, use cURL library).

$json = file_get_contents('http://onleague.stormrise.pt:8031/OnLeagueRest/resources/onleague/Utils/Countries ');

$data = json_decode($json, TRUE);

$countries = array(); 

foreach($data['data']['item'] as $item) {
    $countries[] = $item['description'];
}

CodePad .

当然,要处理$json是否为FALSE(请求错误).

Of course, handle if $json is FALSE (error with request).

或者,如果使用> = PHP 5.3.

Alternatively, if using >= PHP 5.3.

$countries = array_map(function($item) {
    return $item['description'];
}, $data['data']['item']); 

CodePad .

这篇关于PHP函数从Web服务获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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