I have this code:
<?php
$jsonurl = "http://api.wipmania.com/json";
$jsonfgc = file_get_contents($jsonurl);
$json = json_decode($jsonfgc, true);
foreach ( $json["address"] as $address => $country_code )
{
echo $address["country_code"];
}
?>
However, when I print this out, I only get "cccccr". I try just echo
ing $country_code
but I get "North AmericaNA-United StatesUS-". Any help?
If you're actually trying to grab the country code, do the following:
echo $json['address']['country_code'];
A loop is not required there.
I try just echoing $country_code but I get "North AmericaNA-United StatesUS-". Any help?
For an explanation as to why this is happening:
You probably didn't add any linebreaks in your code. So it appears as if it's a single string. It's actually not.
Try:
foreach ( $json["address"] as $address => $country_code )
{
echo $country_code."<br/>
";
}
The output should be:
North America
NA
-
United States
US
-
Why you are using $address
as array it is just an index.
If you want only country code
Use:
//foreach ( $json["address"] as $address => $country_code )
//{
echo $json["address"]["country_code"];
//}
Try printing it out first, it will make it much easier to figure it out. (for debuggin ofcourse)
var_dump($json); // or print_r( $json ); if you want
To print keys and values you can use this:
foreach( $json['address'] AS $index => $value ) {
echo "$index - $value<br />";
}
<?php
$jsonurl = "http://api.wipmania.com/json";
$jsonfgc = file_get_contents($jsonurl);
$json = json_decode($jsonfgc, true);
echo $json["address"]["country_code"]; //if json return single value
//if return multiple then execute it
foreach ( $json as $key => $val )
{
if($key=="address"){
echo $json[$key]['country_code'];
};
}
?>
You don't need foreach
here. Just use:
echo $json["address"]["country_code"];
Note that in PHP 5.4 and later, your code would actually generate warnings: "Warning: Illegal string offset 'country_code'". In your foreach
loop (which enumerates all properties in the object), $address
is a string (the property name), not an array.