2012-05-29 149 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']); 

無需呼應成一個字符串參數...與.正好連接。