'PHP modify fetched variable and return to frontend for JS

Im fetching Product Attributes from Woocommerce, and echo them out in a script tag as variable to use with javascript in frontend. This might be a bad practice, feel free to enlighten me.

Example:

Product Attributes:

Total height: 43m

Total length: 55m

PHP queries "Total-height" as Attribute Name and "43m" as Attribute Value. PHP replaces empty space with "-". I can't define a javascript var with "-" in var name. Example: var Total-height = "43m";

How could I fix this issue? Here is my code. Thanks in advance.

function product_attribute_dimensions(){
    global $product;
    
foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {
    // Get the attribute label
    $attribute_label_name = wc_attribute_label($taxonomy);
    $value = $product->get_attribute($taxonomy);
        if ($value) {
            $label = get_taxonomy($taxonomy)->labels->singular_name;
    
            $profile_one = $value;
            echo '<script>' . $attribute_label_name . ' = "' . $value . '";
            </script>';
                
        }

}


Solution 1:[1]

As I understand the generated string in the variable "$attribute_label_name" is the problem? Take a look at https://www.php.net/manual/de/function.str-replace.php

With this native PHP function you can search for a character (eg."-") and replace with something else (eg. "_") echo '<script>' . str_replace("-", "_", $attribute_label_name) . ' = "' . $value . '";

But as you said, this might not be the best approach. I personally would add this kind of information into a "data-X" HTML attribute in some HTML element and would extract this in my JS. Similar to this:

<div id="some_element" class="could be hidden" data-total-height="<?= $value ?>"></div>

You could Query something like this with jQuery $("#some_element").attr("data-total-height")

Solution 2:[2]

function product_attribute_dimensions() {
    global $product;

    $product_atrributes = array();
    foreach ($product->get_attributes() as $taxonomy => $attribute_obj) {
        // Get the attribute label
        $attribute_label_name = wc_attribute_label($taxonomy);
        $attribute_label_name = str_replace(' ', '_', $attribute_label_name);
        $value = $product->get_attribute($taxonomy);
        if ($value) {
            $product_atrributes[$attribute_label_name] = $value;
        }
    }
    echo '<script type="text/javascript">var product_atrributes = ' . json_encode($product_atrributes) . ';</script>';
}

Now you can use in JS like product_atrributes.Total_height.value This way the redundant script tag also can be avoided.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 clash
Solution 2 mujuonly