5

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

I need a simple PHP function to list the 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"
 }
 ]
 }
}
asked May 22, 2011 at 11:00

1 Answer 1

6

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.

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

Alternatively, if using>= PHP 5.3.

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

CodePad.

answered May 22, 2011 at 11:02
2
  • Something is not right?! I'm getting wrong values on my array print_r($countries); Array ( [0] => g [1] => ) Commented May 22, 2011 at 18:26
  • 1
    @Carlos You must be doing something wrong, because it definitely works. Commented May 22, 2011 at 22:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.