简体   繁体   中英

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 ): 在此处输入图片说明

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" ]

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)); ?>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM