• Mitko

    (@apendix)


    Hello!

    Sometimes I get this error:
    E_ERROR was caused by line 3 of the file /wp-content/plugins/insert-php-code-snippet/shortcode-handler.php(99) : eval()’d code. Error: Cannot redeclare getWaterLevel() (previously declared in /wp-content/plugins/insert-php-code-snippet/shortcode-handler.php(99) : eval()’d code:3)

    Here is the code I try to insert:

    <?php
    
    function getWaterLevel($data, $stationName) {
        foreach ($data as $entry) {
            if ($entry->Station == $stationName) {
                return $entry->{'Water Level (cm)'};
            }
        }
        return null;
    }
    
    // The URL containing the JSON data
    $url = "https://example.com/water_data.json";
    
    // Use file_get_contents to fetch the contents of the URL
    $response = file_get_contents($url);
    
    // Check if the request was successful
    if ($response !== false) {
        // Use json_decode to parse the JSON data into a PHP object
        $data = json_decode($response);
        
        if ($data !== null) {
            // Test the function
            $stationName = "SomeStation";
            $waterLevel = getWaterLevel($data, $stationName);
            
            // Print the result
            echo  $waterLevel;
        } else {
            // Print an error if the JSON could not be parsed
            echo "Error: Could not parse JSON data.";
        }
    } else {
        // Print an error if the request was unsuccessful
        echo "Error: Could not fetch data from the URL.";
    }
    
    ?>

    What could cause this?
    I have to delete the autosaved version in wp_post table in order to be able to open and edit the page!

    Kind Regards!

Viewing 1 replies (of 1 total)
  • “Cannot redeclare getWaterLevel()” error, indicates that the function getWaterLevel() is being declared more than once in the same code. This often happens when the same function is declared in the same scope multiple times.
    So before declaring the getWaterLevel() function, check if it already exists.

    if (!function_exists('getWaterLevel')) {
        function getWaterLevel($data, $stationName) {
            foreach ($data as $entry) {
                if ($entry->Station == $stationName) {
                    return $entry->{'Water Level (cm)'};
                }
            }
            return null;
        }
    }

    Please update the snippet code and let us know, if the issue persists.

Viewing 1 replies (of 1 total)

The topic ‘Errors when I try to save a page that uses the PHP Code snippet’ is closed to new replies.