How do I run the PHP function htmlspecialchars()
on an array of array objects?
I have the following code:
$result_set = Array
(
[0] => Array
(
[home_id] => 1
[address] => 4225 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 76798
)
[1] => Array
(
[home_id] => 8
[address] => 4229 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 75093
)
);
// this doesn't work since $result_set is an array of arrays and htmlspecialchars is expecting a string
htmlspecialchars($result_set, ENT_QUOTES, 'UTF-8'));
UPDATE:
Please note that even though there are quite a few answers below, none of them work for an array-of-arrays. The answers below only work for simple arrays.
I've tried the following, but it doesn't work:
array_walk_recursive($result_set, "htmlspecialchars", array(ENT_QUOTES,'UTF-8'))
I get the following error: htmlspecialchars() expects parameter 2 to be long, string given
UPDATE 2
When I try:
function cleanOutput(&$value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
print_r($result_set);
print('-------');
print_r(array_walk_recursive($result_set, "cleanOutput"));
I get the following, undesired, output:
Array
(
[0] => Array
(
[home_id] => 1
[address] => 4225 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 76798
)
[1] => Array
(
[home_id] => 8
[address] => 4229 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 75093
)
)
-------1
UPDATE 3
When I try:
function cleanOutput(&$value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
$result_set = Array
(
[0] => Array
(
[home_id] => 1
[address] => 4225 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 76798
)
[1] => Array
(
[home_id] => 8
[address] => 4229 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 75093
)
);
$cleanedOutput = array();
foreach ($result_set as $rs) {
$cleaned[] = array_map("cleanOutput", $rs);
}
print_r($cleanedOutput);
I get the following, undesired, results:
{'homes' : []}