Francesco Gatto
Francesco Gatto

Reputation: 3

json_encode adds double quotes instead of spaces

I am trying to work around a problem reading data from mysql and passing them to my page throught php. My task is to insert data read from mysql directly into a js function. The code is:

while($row = $query_ope->fetch_assoc()){
  $data = array("str_id" => $row['Id'],
                "str_rag_sociale" => $row['Rag_Sociale'],
                "str_indirizzo" => $row['Indirizzo'],
                "att_luogo" => json_decode($row['Comune']),
                "str_cap" => $row['Cap'],
                "str_reparto" => $row['Reparto']
                );
  $content .= '<tr class="cal_body">'.
                <td class="btn_icon icon icon-setup" onclick=modUt('.json_encode($data).')></td>'.
              '</tr>';

The problem now is that data from db fields that contains spaces inside it (for example, when $row['Comune'] = "some text") is parsed as followed:

onclick=modUt({...,"att_luogo" : "some" text","str_cap"....})

putting a double quotes after first word some, and this is a problem because my js function fail. I am getting crazy trying to understand why.

Upvotes: 0

Views: 810

Answers (1)

Musa
Musa

Reputation: 97672

You have to html encode your html attribute

$content .= '<tr class="cal_body"> 
            <td class="btn_icon icon icon-setup" onclick="'.htmlspecialchars('modUt('.json_encode($data).')').'"></td>'.
          '</tr>';

Upvotes: 3

Related Questions