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.

Niclas Gleesborg
  • 566
  • 1
  • 5
  • 23

3 Answers3

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
}
?>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
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"?

Sergiu Paraschiv
  • 9,929
  • 5
  • 36
  • 47
  • 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. – Niclas Gleesborg Jan 23 '15 at 16:01
  • As Quentin said: `htmspecialchars` (http://stackoverflow.com/questions/2109583/whats-the-best-practice-to-set-html-attribute-via-php) - so `htmlspecialchars(json_encode($foo))` and then `json_decode(htmlspecialchars_decode($bar))`. – Sergiu Paraschiv Jan 23 '15 at 16:03
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.