0

I'm developing a website using PHP which enables the creation on poster automatically. The users can choose between color themes which are defined on a php file like this:

$f_1 =array(
    "1" => "#1e354c ",
    "2" => "#ebcc85",
    "3" => "#133745"
    );
$f_3 =array(
    "1" => "#1e354c",
    "2" => "#b5cd9c",
    "3" => "#133745"
    );

$themes = array(
          "Tema 1"        => json_encode($f_1),

          "Tema 2"          => json_encode($f_3)
          );

echo "<select class='form-control' id='themeselect' onchange='updatePoster()'>";
foreach($themes as $cc => $name) {  
    echo '<option value="' . $name . '">' . $cc . '</option>';    
}
echo "</select>";

The JSON ecoding of $f_1 looks like this;

"{\"1\":\"#1e354c \",\"2\":\"#ebcc85\",\"3\":\"#133745\"}"

The problem is that the value of "Tema 1" is "{"

I also tried to use serialize() instead of json_encode() but that didn't work either.

0

3 Answers 3

2

" has special meaning in an attribute value delimited by " characters.

Use htmlspecialchars() to convert non-HTML data to HTML before inserting in an HTML document.

foreach($themes as $cc => $name) {  
?>
    <option
        value="<?php echo htmlspecialchars($name); ?>">
        <?php echo htmlspecialchars($cc); ?>
    </option>
<?php
}
?>
Sign up to request clarification or add additional context in comments.

Comments

1

json_encode returns a string. It's your job as a developer to use it properly. While \" is the proper way of escaping double quotes in a double quoted string in PHP, that's not the case with HTML attributes. &quot; is.

So I bet the generated HTML looks like this:

<select  ...>
    <option value="{"1":...>Tema1</option>
</select>

Notice why updatePoster tells you the selected value is "1"?

2 Comments

I realize that there is a problem with the encoding but I don't know how to fix it. I need the array to be able to be serialized/unencoded by another PHP script at a later point.
As Quentin said: htmspecialchars (stackoverflow.com/questions/2109583/…) - so htmlspecialchars(json_encode($foo)) and then json_decode(htmlspecialchars_decode($bar)).
0

You can also change this echo statement:

echo '<option value="' . $name . '">' . $cc . '</option>';

to

echo "<option value='$name'>$cc</option>";

so the value is delimited by single quotes instead of double quotes. This should also solve your problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.