adlerka.top/lib/script_data.php

18 lines
839 B
PHP
Raw Normal View History

2024-02-05 21:21:04 +01:00
<?php
2024-02-05 22:56:20 +01:00
function generateScriptData($phpArray):string {
2024-02-05 22:52:44 +01:00
// 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
2024-02-05 22:56:20 +01:00
$out = "<script>";
2024-02-05 22:52:44 +01:00
foreach ($phpArray as $key => $value) {
$escapedKey = addslashes($key); // Escape special characters in the key
$escapedValue = addslashes($value); // Escape special characters in the value
2024-02-05 21:21:04 +01:00
2024-02-05 22:56:20 +01:00
$out .= "localStorage.setItem('$escapedKey', '$escapedValue');";
2024-02-05 22:52:44 +01:00
}
2024-02-05 22:56:20 +01:00
$out.= "</script>";
2024-02-05 22:52:44 +01:00
} else {
2024-02-05 22:56:20 +01:00
$out = "<script>console.error('Invalid PHP array. Must be single-level and associative.');</script>";
2024-02-05 22:52:44 +01:00
}
2024-02-05 22:56:20 +01:00
return $out;
2024-02-05 21:21:04 +01:00
}