【问题标题】:PHP function to get data from web service用于从 Web 服务获取数据的 PHP 函数
【发布时间】:2011-08-30 13:22:36
【问题描述】:

如何使用 PHP 从this web service 获取数据?

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

网络服务数据

{
   "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"
         }
      ]
   }
}

【问题讨论】:

    标签: php web-services json


    【解决方案1】:

    假设allow_url_fopenphp.ini 中打开(如果没有,请使用cURL 库)。

    $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.

    当然,如果$jsonFALSE 则处理(请求出错)。

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

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

    CodePad.

    【讨论】:

    • 有什么不对吗?!我的数组 print_r($countries); 上的值错误数组 ( [0] => g [1] => )
    • @Carlos 你一定是做错了什么,因为它确实有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 2018-04-24
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多