0

I want to use these icons in a dynamically generated PHP image so people can embed the weather on their webpage.

Right now I'm using met.no's weather service, which provides a neat property called "symbol" and is an integer. 1 = Sunny, 2 = Cloudy etc. A Pull Request on the weather icons repo includes mapping for met.no which is cool, because I can call echo "<i class='wi wi-yrno-$symbol'></i>"; and get the right icon always.

But I don't know how to do this using PHP's image creation functions. In Javascript, you can do this: Programmatically get FontAwesome unicode value by name , but how would I do this in PHP? I think I need to just make an array of array("wi-yrno-1 => "(unicode escape code here)", "wi-yrno-2" => "(another escape code here) ... but I wondered if there was a better way.

Community
  • 1
  • 1
DrFrankly
  • 61
  • 3
  • 8

1 Answers1

0

I am assuming you are generating an image on your server and then sending that content to the browser.

The JavaScript example you gave is irrelevant. Mainly because the font is already loaded and mapped to a class name. In PHP you would have to recreate this mapping. A simple mapping of the symbol to a decimal value would work. E.g.

$symbols = [0 => '&#xf00d;', 1 => ..., 2 => ..., ...];

Once you have the mapping set up, you need the absolute path to the font file you are using. After you know that you would use imagettftext to draw text on the image with the given ttf font file. It must be a ttf font file (hence the name of the function).

// the symbol response from the met.no request
$symbolIntFromApi = 0;

// the mapping for the decimal characters
$symbols = [0 => '&#xf00d;'];

// create the image
$image = imagecreatetruecolor(1000, 1000);

// set background color to white
imagefill($image, 0, 0, imagecolorallocate($image, 255, 255, 255));

// write the text using the given font
imagettftext($image, 12, 0, 20, 20, 0, realpath('./font/weathericons-regular-webfont.ttf'), $symbols[$symbol]);

// save the image
imagepng($image, 'test.png');
honerlawd
  • 1,499
  • 11
  • 10
  • Thanks for that. I assumed that was the case, but sometimes when I'm looking for answers to problems I'm having, I get blown away that language W can do X, Y and Z, when they seem like incompatible technologies. – DrFrankly Apr 26 '16 at 07:29