Cofem/lib/script_data.php

19 lines
880 B
PHP

<?php
declare(strict_types=1);
function generateScriptData($phpArray):string {
// Check if the array is associative and single-level
if (is_array($phpArray) && count($phpArray) > 0 && count(array_filter(array_keys($phpArray), 'is_string')) === count($phpArray)) {
// Generate JavaScript code to save each array element to local storage
$out = "<script>";
foreach ($phpArray as $key => $value) {
$escapedKey = addslashes(strval($key)); // Escape special characters in the key
$escapedValue = addslashes(strval($value)); // Escape special characters in the value
$out .= "localStorage.setItem('$escapedKey', '$escapedValue');";
}
$out.= "</script>";
} else {
$out = "<script>console.error('Invalid PHP array. Must be single-level and associative.');</script>";
}
return $out;
}