keeping single-quotes in http_build_query()?
I'm wanting to use http_build_query to change an array to html tag properties. Problem is, it's changing my single-quoted values into %27
. So if I have
http_build_query( ar开发者_Go百科ray("type"=>"'hidden'", ... ), '', ' ' );
I get
<input type=%27hidden%27 ...>
How can I get around this?
you could add urldecode()
in front of the http_build_query
like:
<?php
urldecode(http_build_query( array("type"=>"'hidden'", ... ), '', ' ' ));
?>
http_build_query()
was designed to turn an array of parameters into a URL. Not to build an HTML tag. You can do a few things:
Add it all manually
<input type="<?php echo htmlspecialchars($array['type']); ?>" ...
Build a helper function
function buildArgs($array) { $ret = ''; foreach ($array as $key => $value) { $ret .= ' ' . htmlspecialchars($key, ENT_QUOTES) . '="' . htmlspecialchars($value) . '"'; } return trim($ret); } <input <?php echo buildArgs(array('type'=>'hidden', 'name'=>'foo')); ?>>
Would yield you:
<input type="hidden" name="foo" >
I guess you could get around this doing a rawurldecode()
on the result, but this really isn't what http_build_query
was intended for. And won't it put a &
between the name/value pairs anyway, making the output unusable as a input
element?
You could use one of the XML classes to do this but I'm not sure it's worth the effort. Where are you using this?
No quotes are required in your array with this function:
A one-liner for creating string of HTML attributes (with quotes) from a simple array:
$attrString = str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";
Example:
$attrArray = array("id" => "email",
"name" => "email",
"type" => "email",
"class" => "active large");
echo str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";
// Output:
// id="email" name="email" type="email" class="active large"
Recursive function to make hidden INPUTs:
$buildInputs = function($params, $prefix = '') use (&$buildInputs) {
foreach ($params as $k => $v) {
if (is_array($v)) {
$buildInputs($v, $k);
} else {
if ($prefix) {
$k = $prefix.'['.$k.']';
}
echo '<input type="hidden" name="'.$k.'" value="'.htmlspecialchars($v).'">';
}
}
};
$buildInputs($postdata);
精彩评论