Max Lynn Max Lynn - 4 months ago 17
JSON Question

Using a Json_encode to then be passed to a data attribute

I'm struggling to set an array to a data attribute. I can see that it is logging in the DOM with the below image ( a complete mess ):enter image description here

The attribute data-category is the one in focus. My php that is producing this seems to add ='' if there is a space in the converted php array. This is the php that is converting this over to a json array:

$arr = array();
foreach($cats as $cat) {
array_push($arr, $cat->cat_name);
}

data-category="<?php echo json_encode($arr); ?>"


What is it that I'm missing to convert this to a proper json structure for me to work with in the js.

I'm looking to have an outcome something similar to this:

Array [ "Customer Service", "Finance", "HR", "Marketing", "Operations", "Sales", "Technology" ]

Answer

My php that is producing this seems to add ='

That isn't what the PHP is producing.

You are looking at it in a DOM inspector. That shows the results of parsing the HTML to a DOM and then serialising it back to HTML for display.

If you want to look at the output of the PHP then you need to look at View Source and not Inspect Element.


JSON uses " to delimit strings.

An HTML attribute value that is delimited by " characters will be terminated by " characters.

To represent a " as data in an HTML attribute value; use &quot;.

Run the output of json_encode through htmlspecialchars before outputting it into the HTML.

data-category="<?php echo htmlspecialchars(json_encode($arr)); ?>"