Home  >  Article  >  Backend Development  >  How to convert ip to city in php

How to convert ip to city in php

藏色散人
藏色散人Original
2021-12-07 09:31:342489browse

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.

How to convert ip to city in php

#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 = &#39;具体的IP地址&#39;;
$a = &#39;http://www.cip.cc/&#39;.$ip;
$opts = array(
    &#39;http&#39;=>array(
        &#39;method&#39;=>"GET",
        &#39;header&#39;=>
            "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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn