2012-05-29 53 views
2

我想在一个表单输入值,显示用户的国家(根据其IP)。IP地址解析使用PHP回声

这里是我到目前为止的代码..

<input style="display:block" type="text" name="country" id="country" value="<?php    
$pageContent = file_get_contents('http://freegeoip.net/json/echo $_SERVER['REMOTE_ADDR']'); 
$parsedJson = json_decode($pageContent); 
echo $parsedJson->country_name; ?>" /> 

我使用PHP JSON解码从中获取数据“http://freegeoip.net/json/(IP地址)”。

该网站地址解析为IP地址,并返回一个国家的名字。

我想要做的是能够在用户的IP地址来替换成网址,然后将返回用户的国家名称。我能想到的最好的办法是通过使用

<?php echo $_SERVER['REMOTE_ADDR']; ?> 

但是当我把它放在我收到了服务器错误。

我怎么会去这样做呢?

+3

没有进攻中找到,但请不要对基本PHP语法学习的有点... –

+0

http://php.net/manual/en/language.types.string.php和http://www.php.net/manual/en/language.operators.string.php – webbiedave

回答

11
$pageContent = file_get_contents('http://freegeoip.net/json/' . $_SERVER['REMOTE_ADDR']); 

不能在函数中使用echo。相反,你应该使用concatenating operator

此外,更好的代码会是这样的:

<?php    
$pageContent = file_get_contents('http://freegeoip.net/json/' . $_SERVER['REMOTE_ADDR']); 
$parsedJson = json_decode($pageContent); 
?> 
<input style="display:block" type="text" name="country" id="country" value="<?php echo htmlspecialchars($parsedJson->country_name); ?>" /> 
2
$pageContent = file_get_contents('http://freegeoip.net/json/' . $_SERVER['REMOTE_ADDR']); 

无需呼应成一个字符串参数...与.正好连接。