1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PHP】連想配列をHTMLタグの属性列にする

Last updated at Posted at 2025-04-03

属性にする

なーんかよく書くなぁというコード。

function join_array_as_attrs($ary) {
    $s = '';

    foreach ($ary as $key => $val) {
        $s .= safe($key) .'="'. safe($val) .'" ';
    }

    return $s;
}

safe()htmlspecialchars()のラッパー。
よくわからんけどこの関数は何回か書いてる気がする。

タグを構成するときに

function create_momonga_img($attrs) {
    $tag = '<img src="momonga.png" ';
    $tag .= join_array_as_attrs($attrs);
    $tag .= '>';
    return $tag;
}

こんな感じで使う。
$attrsは外部入力の可能性もあるからsafe()でエスケープしておくのがキモ。

おわり。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?