使用 HTML 实体转换数组和对象


Convert array and object with HTML entities

我正在尝试编写一段代码,它将递归地转换数组或对象中的每个字符串,以确保在输入框中显示引号的安全性。

这是我写的数组,其中包含我从其他人那里看到的部分。它适用于对象但不适用于数组,它似乎到达第二个数组,并输出一个字符串"null"

function fixQuotes($item)
{
    if (is_object($item)) {
        foreach (get_object_vars($item) as $property => $value) {
            //If item is an object, then run recursively
            if (is_array($value) || is_object($value)) {
                fixQuotes($value);
            } else {
                $item->$property = htmlentities($value, ENT_QUOTES);
            }
        }
        return $item;
    } elseif (is_array($item)) {
        foreach ($item as $property => $value) {
            //If item is an array, then run recursively
            if (is_array($value) || is_object($value)) {
                fixQuotes($value);
            } else {
                $item[$property] = htmlentities((string)$value, ENT_QUOTES);
            }
        }
    }
}
如果

数组是两个数组深,它就不会保存数组,它现在正在工作,而且它缺少数组的返回。感谢您的阅读。

这是固定代码的副本,如果将来有人需要执行此操作的脚本。

function fixQuotes($item)
{
    if (is_object($item)) {
        foreach (get_object_vars($item) as $property => $value) {
            //If item is an object, then run recursively
            if (is_array($value) || is_object($value)) {
                $item->$property = fixQuotes($value);
            } else {
                $item->$property = htmlentities($value, ENT_QUOTES);
            }
        }
        return $item;
    } elseif (is_array($item)) {
        foreach ($item as $property => $value) {
            //If item is an array, then run recursively
            if (is_array($value) || is_object($value)) {
                $item[$property] = fixQuotes($value);
            } else {
                $item[$property] = htmlentities((string)$value, ENT_QUOTES);
            }
        }
        return $item;
    }
}