Menü schliessen
Created: March 15th 2024
Last updated: March 16th 2024
Categories: Common Web Development,  Php
Author: Tim Fürer

PHP: How to automatically generate IcoMoon HTML

Tags:  function,  guide,  PHP
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In modern web development, icons play a crucial role in enhancing user interfaces, improving accessibility, and conveying meaning in a visually appealing manner. One popular approach to incorporating icons into web projects is by utilizing icon fonts like IcoMoon. However, writing out the entire HTML structure required for these icons can be time-consuming. In this article, we'll explore a PHP helper function that simplifies the process of generating HTML for IcoMoon icons using an IcoMoon selection.json file.


How do I get a selection.json

A selection.js file comes with your generated IcoMoon font pack:

If you're missing the file, you you can simply regenerate your IcoMoon pack.


Icomoon Helper Function

<?php

function icomoon($name, $classes = '') {
    static $selection = null;

    if (!$selection) {
        $selection_json_path = 'path/to/selection';

        if (!file_exists($selection_json_path)) {
            throw new Exception("Icomoon appears to be missing or in an unusual location.");
        }

        $selection = json_decode(
            file_get_contents($selection_json_path)
        );
    }

    $icon_prefix = $selection->preferences->fontPref->prefix;

    $path_count = 0;

    foreach ($selection->icons as $icon) {
        if ($icon->properties->name === $name) {
            if (isset($icon->properties->code) && !empty($icon->properties->code)) {
                $path_count = 1;

                if (isset($icon->properties->codes)) {
                    $path_count = count($icon->properties->codes);
                }
            }

            break;
        }
    }

    if (1 > $path_count) {
        throw new UnexpectedValueException("Unknown icon ({$name})");
    }

    $handle = $icon_prefix . $name;

    ob_start();

    ?>

    <span class="<?= $handle ?> icomoon-icon <?= $classes ?>">
        <?php

        if ($path_count > 1) {
            foreach (range(1, $path_count) as $index) {
                ?>

                <span class="path<?= $index ?>"></span>

                <?php
            }
        }

        ?>
    </span>

    <?php

    return ob_get_clean();
}

?>

How the Function Works

Let's break down the key components of this helper function:

  • Static Cache: The function utilizes a static variable $selection to cache the parsed content of the Icomoon selection.json file. This ensures that the file is only read and parsed once, improving performance.
  • Reading Selection.json: The function expects the path to the selection.json file to be defined in $selection. It reads and decodes the JSON content, then stores it in the $selection variable.
  • Generating HTML: The function accepts the name of the desired icon and an optional string of additional CSS classes. It searches for the corresponding icon within the parsed JSON data and extracts relevant information such as the icon prefix and the number of paths (if any).
  • Output HTML: Using output buffering (ob_start() and ob_get_clean()), the function constructs HTML markup for the icon, applying appropriate classes and automatically handling multiple paths if necessary.
  • Exception Handling: If the requested icon is not found or if the path count is less than 1, the function throws an UnexpectedValueException.

Usage

Here's how you can use the icomoon() function in your PHP projects:

<?php

echo icomoon('name', 'custom-class');

?>

Replace 'name' with the name of the desired icon from your Icomoon selection, and 'custom-class' with any additional CSS classes you want to apply. Mind that the name excludes the icon prefix.