PHP function to retrieve data from a web service

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

I need a simple PHP function to list countries.

Web service data

{
   "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"
         }
      ]
   }
}
+5
source share
1 answer

Assuming it is allow_url_fopenincluded in php.ini(if not, use the 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 .

Of course, $jsonthere is an if descriptor FALSE(a request error).

Alternatively, when using> = PHP 5.3.

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

Codepad .

+6
source

All Articles