How can I style a PHP echo text?

How can I style a PHP echo text?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Styling Output from echo: The Real Problem in Your Code

You cannot style text directly inside a PHP echo statement that outputs raw data because echo does not know how to handle HTML tags or CSS classes. When you write echo $ip['cityName'];, the server sends the string "London" to the browser as plain text. If you try to wrap it in <span> tags or add a class attribute inside the echo, PHP treats those characters as literal data to be printed, not as instructions to render styled elements.

Furthermore, your current code snippet contains a critical logical flaw that prevents styling from working at all: you are returning a JSON object directly from the function without decoding it properly before accessing the keys, and more importantly, you are likely mixing up the variable types. The countryCityFromIP function returns an associative array (after json_decode), but your if statement checks if $ip is set based on $_REQUEST['ip']. If the API call fails or returns null, accessing $ip['cityName'] will throw a fatal error before any styling can even be attempted.

To actually style the output, you must separate data retrieval from presentation. In PHP, this is best achieved by echoing HTML fragments that contain your variables. Instead of echo $ip['cityName'];, you should construct a string or use short tags to inject the variable into an HTML element. Here is how you modify the logic:

if (isset($_REQUEST['submit'])) {
    $data = countryCityFromIP($_REQUEST['ip']);
    
    // Validate that the data exists before trying to access keys
    if ($data && isset($data['cityName']) && isset($data['countryName'])) {
        echo '<div class="location-result">';
            echo '<span class="city">' . htmlspecialchars($data['cityName']) . '</span>, ';
            echo '<span class="country">' . htmlspecialchars($data['countryName']) . '</span>';
        echo '</div>';
    } else {
        echo 'Unable to resolve IP address.';
    }
}

The key change here is htmlspecialchars(). You cannot just echo raw user input or API data directly into HTML because it opens a massive XSS vulnerability. If the API returns "London, ON", and you wrap it in <span class="city">, that's fine. But if the API ever returns malicious script tags, your application becomes compromised. The function ensures the output is safe to style without breaking the page structure.

Next, you need to define the CSS that applies to those classes. Since echo only outputs the HTML string, the browser will ignore it unless a stylesheet exists. You can add this to a <style> block in your head or an external .css file:

.location-result {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background-color: #f4f4f9;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.city {
    font-weight: bold;
    color: #333;
}

.country {
    color: #666;
    font-size: 0.9em;
}

There is a significant trade-off in how you handle the API request itself. Your current implementation uses file_get_contents to fetch JSON data. While this works for simple scripts, it blocks the execution of your script until the remote server responds. If the network is slow or the API times out, your user is stuck waiting. In a production environment, using cURL with asynchronous requests or checking headers first is more robust. Additionally, hardcoding the API key in your source code, as shown in your snippet, is a security risk. Keys should be stored in environment variables or a configuration file outside the web root.

If you are looking for a more secure and scalable way to handle this logic, consider leveraging a framework like Laravel. Frameworks abstract away the HTML escaping, route handling, and dependency injection, making it much harder to accidentally expose raw data or forget to escape output. For instance, using Blade templating engines allows you to mix PHP variables with HTML cleanly without manually constructing echo strings for every piece of text. This approach ensures that styling decisions are separated from business logic, reducing the chance of errors when modifying your UI later.

Ultimately, the issue isn't that echo cannot display styled text; it's that you must explicitly provide the HTML structure and ensure the data is sanitized before being printed. By wrapping variables in valid HTML tags and applying CSS classes to those tags, you achieve the desired styling while maintaining security and code integrity.

Our network