Fix script on open page

This commit is contained in:
2024-02-05 22:52:44 +01:00
parent 2cade060cf
commit 7dbb38913b
4 changed files with 84 additions and 63 deletions

View File

@@ -1,9 +1,17 @@
<?php
function generateScriptData($input) :string
{
// Convert PHP array to JSON string
$jsonString = json_encode($input);
function generateScriptData($phpArray) {
// 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
echo "<script>";
foreach ($phpArray as $key => $value) {
$escapedKey = addslashes($key); // Escape special characters in the key
$escapedValue = addslashes($value); // Escape special characters in the value
// Output JavaScript code with the JSON string
return "<script>let pageData = JSON.parse('$jsonString');</script>";
echo "localStorage.setItem('$escapedKey', '$escapedValue');";
}
echo "</script>";
} else {
echo "<script>console.error('Invalid PHP array. Must be single-level and associative.');</script>";
}
}