底辺SE奮闘記

年収300万SEブログ

【PHP・meyfa/php-svg】imagettftext(): any2eucjp(): invalid code in input string というエラーが出る

meyfa/php-svg 便利ですよね

github.com

今日もこれの話題です。

現象

サーバによっては、

imagettftext(): any2eucjp(): invalid code in input string

というエラーが出る場合があります。

全角スペースなどの一部特殊文字を描画しようとすると発生する様子。

meyfa/php-svgで通常文字列を描画しようとすると下記の様なコードになります。

<?php
(new SVGText("はろー わーるど", $x, $y))->setFont($font)
    ->setSize($fontSize)
    ->setStyle('fill', $color)
    ->setStyle('stroke', $color)
    ->setStyle('stroke-width', $strokeWidth)

上記コード("はろー"と"わーるど"の間に全角スペースがあります)が題のようなエラーが出て正常に動作しない場合は、下記の様にコードを変更します。

<?php
$text = "はろー わーるど";
$text = mb_encode_numericentity($text, array(0x0080, 0xffff, 0, 0xffff), 'UTF-8');
(new SVGText($text, $x, $y))->setFont($font)
    ->setSize($fontSize)
    ->setStyle('fill', $color)
    ->setStyle('stroke', $color)
    ->setStyle('stroke-width', $strokeWidth)

mb_encode_numericentityという関数を使用するようです。

mb_encode_numericentityのドキュメントは下記の通り。

https://www.php.net/manual/ja/function.mb-encode-numericentity.php

また参考までに第一引数、第二引数に関係するユニコードの対応表は、下記の通り

unicode.ninpou.jp

上記例のコードですと0x0080ですので、「€」以降が変換されるわけです。

以上。