PHP - 带有 json 个参数的 printf

PHP - printf with json arguments

我试图在 printf 编码的 json 数组中作为参数传递。但是,由于 json 数组的性质,它会在 printf 中产生错误:printf(): Too few arguments

有没有办法像这样在 printf 方法中传递编码的 json 数组:

$val   = 10;
$min   = 0;
$max   = 100;
$steps = array( 1, 0.1, 0.01 );
$units = array( 'px', 'em', '%' );

printf(
    '<input type="range" value="%d" min="%d" max="%d" step="0.01" data-steps="%s" data-units="%s">',
    floatval( $val ),
    floatval( $min ),
    floatval( $max ),
    json_encode( $steps ),
    json_encode( $units )
);

谢谢

你的代码很好,但它生成了这段 HTML

<input type="range" value="10" min="0" max="100" step="0.01"
       data-steps="[1,0.1,0.01]" data-units="["px","em","%"]">

由于 JSON 内容中包含双引号而无效。

您用来生成 HTML 的任何动态内容都必须正确 HTML 编码。使用 htmlspecialchars() to encode the values returned by json_encode() before passing them to printf() 生成有效的 HTML:

$val   = 10;
$min   = 0;
$max   = 100;
$steps = array( 1, 0.1, 0.01 );
$units = array( 'px', 'em', '%' );

printf(
    '<input type="range" value="%d" min="%d" max="%d" step="0.01" data-steps="%s" data-units="%s">',
    floatval( $val ),
    floatval( $min ),
    floatval( $max ),
    htmlspecialchars( json_encode( $steps ) ),
    htmlspecialchars( json_encode( $units ) )
);

floatval() 返回的值不需要这种处理,因为它们不包含 HTML 个特殊字符。