Home > Article > Backend Development > How to convert ip to city in php
php method to convert IP to city: 1. Create a PHP sample file; 2. Get the specific IP address; 3. Through "function get_tag_data($html,$tag){...}" Just wait for the method to convert the IP to a city address.
#The operating environment of this article: Windows 7 system, PHP version 7.4, Dell G3 computer.
How to convert ip to city in php?
PHP IP address to city actual address:
What I use here Querying the actual IP address through http://www.cip.cc/ temporarily solved my problem (this method will become obsolete when the website http://www.cip.cc/ is discontinued, use with caution)
<?php $ip = '具体的IP地址'; $a = 'http://www.cip.cc/'.$ip; $opts = array( 'http'=>array( 'method'=>"GET", 'header'=> "Accept-language: zh-cn\r\n" . "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; 4399Box.560; .NET4.0C; .NET4.0E)" . "Accept: *//*" ) ); $ctx = stream_context_create($opts); $x = file_get_contents($a,false,$ctx); $result = get_tag_data($x,"pre"); function get_tag_data($html,$tag){ $regex = "/<$tag>(.*?)<\/$tag>/is"; preg_match_all($regex,$html,$matches,PREG_PATTERN_ORDER); return $matches[1];//返回值为数组 ,查找到的标签内的内容 }
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert ip to city in php. For more information, please follow other related articles on the PHP Chinese website!