帮助获取特定阵列。 这个脚本的作用是转到http://www.iplocation.net/index.php?query=223.196.190.40&submit=Query并获取国家,城市,ips等信息,然后将其输出;
[IP Address] => xxx.xxx.xxx.xxx
[Country] => Country
[Region] => Region
[City] => City
[ISP] => Provider
现在我只想让它获得一个数组,即[City]
的数组以下是我现在拥有的代码;
<?php
require_once( "simple_html_dom.php" );
$ip_info = ip_info( $_SERVER['REMOTE_ADDR'], 1 );
print_r( $ip_info );
/**
* It will output...
Array
(
[IP Address] => xxx.xxx.xxx.xxx
[Country] => Country
[Region] => Region
[City] => City
[ISP] => Provider
)
**/
/**
* ip_info()
* @param $ip - IP address you want to fetch data from
* @param $provider IP provider ( 1 = IP2Location, 2 = IPligence, 3 = IP Address Labs, 4 = MaxMind )
* @return array
*/
function ip_info( $ip = "127.0.0.1", $provider = 1 ) {
$indx = array(
1 => 10,
2 => 11,
3 => 12,
4 => 13
);
$data = array();
$url = "http://www.iplocation.net/index.php";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_FRESH_CONNECT, true );
curl_setopt( $ch, CURLOPT_FORBID_REUSE, true );
curl_setopt( $ch, CURLOPT_HEADER, false );
curl_setopt( $ch, CURLOPT_NOBODY, false );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, false );
curl_setopt( $ch, CURLOPT_REFERER, $url );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, "query=".urlencode( $ip )."&submit=Query" );
$response = curl_exec( $ch );
$html = str_get_html( $response );
if ( $table = $html->find( "table", $indx[$provider] ) ) {
if ( $tr1 = $table->find( "tr", 1 ) ) {
if ( $headers = $tr1->find( "td" ) ) {
foreach( $headers as $header ) {
$data[trim( $header->innertext )] = null;
}
}
}
if ( $tr2 = $table->find( "tr", 3 ) ) {
reset( $data );
if ( $values = $tr2->find( "td" ) ) {
foreach( $values as $value ) {
$data[key( $data )] = trim( $value->plaintext );
next( $data );
}
}
}
}
unset( $html, $table, $tr1, $tr2, $headers, $values );
return $data;
}
?>
这将输出
[IP Address] => xxx.xxx.xxx.xxx
[Country] => Country
[Region] => Region
[City] => City
[ISP] => Provider
它必须只是城市,所以如果城市是新纽约的IP而不是输出纽约而不是
[IP Address] => xxx.xxx.xxx.xxx
[Country] => Country
[Region] => Region
[City] => City
[ISP] => Provider
答案 0 :(得分:0)
你可以这样做:
$ip_info = ip_info($_SERVER['REMOTE_ADDR'], 1);
$city = $ip_info->City;
或修改功能的return
仅返回城市,这会使$ip_info
与城市相等:
return $data->City;
如果您真的不关心其他信息,您可以使用简单的foreach
声明在if
循环中专门查找City:
...
foreach( $headers as $header ) {
if (trim( $header->innertext ) == 'City') {
$data[trim( $header->innertext )] = null;
}
}
...
foreach( $values as $value ) {
if (key( $data )) == 'City') {
$data[key( $data )] = trim( $value->plaintext );
next( $data );
}
}
...
return $data->City;