[php] How can I style a PHP echo text?

I have the following code;

<?php
    function countryCityFromIP($ipAddr)
    {
        $url = "http://api.ipinfodb.com/v3/ip-city/?key=5cfaab6c5af420b7b0f88d289571b990763e37b66761b2f053246f9db07ca913&ip=$ipAddr&format=json";
        $d = file_get_contents($url);
        return json_decode($d , true);
    }

    if (isset($_REQUEST['submit']))
    {
       $ip = countryCityFromIP($_REQUEST['ip']);

       //print_r($ip);
       echo $ip['cityName'];
       echo $ip['countryName'];
    }
?>

<form method="post">
    <input type="text" name="ip" />
    <input type="submit" name="submit" value="Find" />
</form>

I need to style "echo $ip['cityName']" here. I tried a lot methods, but I am only getting an error.

This question is related to php css styling

The answer is


echo '<span style="Your CSS Styles">' . $ip['cityName'] . '</span>';

You cannot style a variable such as $ip['countryName']

You can only style elements like p,div, etc, or classes and ids.

If you want to style $ip['countryName'] there are several ways.

You can echo it within an element:

echo '<p id="style">'.$ip['countryName'].'</p>';
echo '<span id="style">'.$ip['countryName'].'</span>';
echo '<div id="style">'.$ip['countryName'].'</div>';

If you want to style both the variables the same style, then set a class like:

echo '<p class="style">'.$ip['cityName'].'</p>';
echo '<p class="style">'.$ip['countryName'].'</p>';

You could also embed the variables within your actual html rather than echoing them out within the code.

$city = $ip['cityName'];  
$country = $ip['countryName'];
?>
<div class="style"><?php echo $city ?></div>
<div class="style"><?php echo $country?></div>

Echo inside an HTML element with class and style the element:

echo "<span class='name'>" . $ip['cityName'] . "</span>";

Store your results in variables, and use them in your HTML and add the necessary styling.

$usercity = $ip['cityName'];
$usercountry = $ip['countryName'];

And in the HTML, you could do:

<div id="userdetails">
<p> User's IP: <?php echo $usercity; ?> </p>
<p> Country: <?php echo $usercountry; ?> </p>
</div>

Now, you can simply add the styles for country class in your CSS, like so:

#userdetails {

/* styles go here */

}

Alternatively, you could also use this in your HTML:

<p style="font-size:15px; font-color: green;"><?php echo $userip; ?> </p>
<p style="font-size:15px; font-color: green;"><?php echo $usercountry; ?> </p>

Hope this helps!


You can "style echo" with adding new HTML code.

echo '<span class="city">' . $ip['cityName'] . '</span>';