Dumbo
Dumbo

Reputation: 14112

Parsing an external HTML page with PHP

I am trying to use the country detection by IP, an API from http://www.hostip.info/use.html

So if you put in your browser something like: http://api.hostip.info/country.php?ip=12.24.25.26

then the page will write "US"...

Now my question is how can I use this in a IF ELSE lopp in my php code? I think I have to parse that HTML page, but at the moment I have no clue, some help would be appriciated!

Thanks.

Upvotes: 1

Views: 1752

Answers (3)

afarazit
afarazit

Reputation: 4984

You could use the following.Change $my_ip to what ever IP you like.

<?php
$my_ip = '12.24.25.26';
$my_country = file_get_contents('http://api.hostip.info/country.php?ip='.$my_ip);

if(strstr($my_country,'US'))
{
    echo $my_country . ' found.';
}
elseif(strstr($my_country,'XX'))
{
    echo 'IP: ' . $my_ip . 'doesn\'t exists in database';
}

Upvotes: 3

scurker
scurker

Reputation: 4753

CURL should do what you need it to do.

$url = "http://api.hostip.info/country.php?ip=[put_your_ip_here]";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);

if(preg_match('/^us$/i', $output)) {
  echo 'Is US';
} else {
  echo 'Something else';
}

Upvotes: 4

alexn
alexn

Reputation: 58962

Since that page does not output anything other than the country code, there is no parsing required. A simple check on the returned HTML will do it.

<?php
$ip = '12.24.25.26';
$country = file_get_contents('http://api.hostip.info/country.php?ip='.$my_ip); // Get the actual HTML

if($country === "US") {
    echo "It is US";
} else {
    echo "It is not US. It is " . $country;
}

Upvotes: 4

Related Questions