无法在PHP

时间:2015-06-24 04:36:09

标签: php arrays

我使用geoplugin来了解用户的国家/地区。在网站上,他们写下以下代码:

echo var_export(unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR'])));

结果是:

array (
'geoplugin_request' => '59.179.68.40',
'geoplugin_status' => 206,
'geoplugin_credit' => 'Some of the returned data includes GeoLite data created by MaxMind, available from http://www.maxmind.com.',
'geoplugin_city' => '',
'geoplugin_region' => '',
'geoplugin_areaCode' => '0',
'geoplugin_dmaCode' => '0',
'geoplugin_countryCode' => 'IN',
'geoplugin_countryName' => 'India',
'geoplugin_continentCode' => 'AS',
'geoplugin_latitude' => '20',
'geoplugin_longitude' => '77',
'geoplugin_regionCode' => '',
'geoplugin_regionName' => NULL,
'geoplugin_currencyCode' => 'INR',
'geoplugin_currencySymbol' => '₨',
'geoplugin_currencySymbol_UTF8' => '₨',
'geoplugin_currencyConverter' => '63.4999',
 )

现在,我试图将它存储在这样的数组中:

$locArray = var_export(unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR'])));

并回显如下位置:

echo $locArray[8];

代码回显第9个元素,而不是像这样完成数组:

array ( 'geoplugin_request' => '59.179.68.40', 'geoplugin_status' => 206, 'geoplugin_credit' => 'Some of the returned data includes GeoLite data created by MaxMind, available from http://www.maxmind.com.', 'geoplugin_city' => '', 'geoplugin_region' => '', 'geoplugin_areaCode' => '0', 'geoplugin_dmaCode' => '0', 'geoplugin_countryCode' => 'IN', 'geoplugin_countryName' => 'India', 'geoplugin_continentCode' => 'AS', 'geoplugin_latitude' => '20', 'geoplugin_longitude' => '77', 'geoplugin_regionCode' => '', 'geoplugin_regionName' => NULL, 'geoplugin_currencyCode' => 'INR', 'geoplugin_currencySymbol' => '₨', 'geoplugin_currencySymbol_UTF8' => '₨', 'geoplugin_currencyConverter' => '63.4999', )

如何从中提取国家名称?

2 个答案:

答案 0 :(得分:0)

$arr = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']));
//  then just access the country index. 
echo $arr['geoplugin_countryCode'];

编辑:

您正在尝试echo $locArray[8];,但没有索引8,因为它是关联数组(索引为字符串的数组)。

答案 1 :(得分:0)

返回一个类似

的数组
array (
  'geoplugin_request' => '192.168.4.188',
  'geoplugin_status' => 404,
  'geoplugin_credit' => 'Some of the returned data includes GeoLite data created by MaxMind, available from http://www.maxmind.com.',
  'geoplugin_city' => '',
  'geoplugin_region' => '',
  'geoplugin_areaCode' => '',
  'geoplugin_dmaCode' => '',
  'geoplugin_countryCode' => '',
  'geoplugin_countryName' => '',
  'geoplugin_continentCode' => '',
  'geoplugin_latitude' => '0',
  'geoplugin_longitude' => '0',
  'geoplugin_regionCode' => '',
  'geoplugin_regionName' => NULL,
  'geoplugin_currencyCode' => NULL,
  'geoplugin_currencySymbol' => NULL,
  'geoplugin_currencySymbol_UTF8' => '',
  'geoplugin_currencyConverter' => '0',
)

然后你可以使用像

echo $locArray['geoplugin_request'];