这是我使用CURL从API中捕获的字符串:
{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3860,-122.0838",
"org": "AS15169 Google Inc.",
"postal": "94040"
}
如何获取国家/地区代码?这就是我一直在尝试的,它只返回整个json字符串:
$json = json_decode($json_raw, true);
$country = $json['country'];
答案 0 :(得分:2)
由于您在对象中输入值,请使用->
进行访问。
<?php
$a = '{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3860,-122.0838",
"org": "AS15169 Google Inc.",
"postal": "94040"
}';
$decode = json_decode($a);
echo $decode->country;// this line
请参阅演示here
正如Surace
所说,即使这应该可以正常工作
<?php
$a = '{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3860,-122.0838",
"org": "AS15169 Google Inc.",
"postal": "94040"
}';
$decode = json_decode($a,true);
echo $decode['country'];
请参阅演示here
答案 1 :(得分:1)
当您将json解码为php格式时,它会将结果作为对象返回,因此您必须使用对象syn文本来访问其属性。 替换
$decode = json_decode($a,true);
$country = $json['country'];
<强>与强>
$decode = json_decode($a);
$country = $json->country;
答案 2 :(得分:1)
我可能会遗漏一些东西,但我认为你的代码没有理由不适合你。 您可以使用json_decode和true选项一样使用返回值作为数组。
<?php
$json_raw = '{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3860,-122.0838",
"org": "AS15169 Google Inc.",
"postal": "94040"
}';
$json = json_decode($json_raw, true);
echo $country = $json['country'];
您可以在此处查看:https://eval.in/483744