Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add HTML code to JSON in PHP?

Tags:

json

php

I need to add folowing html code to JSON using PHP.

<a class="btn btn-mini btn-success" data-toggle="modal" href="#?page=customers-database-edit&id=$1">Edit</a>

If I add this directly than that breaks the JSON code as contains double quotes (").

So I have tried to use the following code:

if(is_string($result))
{
  static $jsonReplaces = array(array('\\', '/', '\n', '\t', '\r', '\b', '\f', '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
  return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $result) . '"';
}
else
  return $result;

Above code generates that html is wrong way:

<a class="\&quot;btn" btn-mini="" btn-success\"="" data-toggle="\&quot;modal\&quot;" href="\&quot;?page=customers-database-edit&amp;id=3\&quot;">Edit&lt;\/a&gt; \n</a>
like image 923
Solver Avatar asked Dec 13 '25 12:12

Solver


1 Answers

The quotes are no problem for json. You just have to rely on the encoding function.

I made this trivial test script, it encodes an array and outputs both, the json encoded string and the array generated from again decoding the string. This proves you get out what you put in, regardless if it contains quotes or not.

Test script:

<?php
$test=array(
  1=>'one',
  2=>'<a class="btn btn-mini btn-success" data-toggle="modal" href="#?page=customers-database-edit&id=$1">Edit</a>',
  3=>'three'
);
$json=json_encode($test);
echo $json."\n\n";
echo print_r(json_decode($json));
?>

Output:

{"1":"one","2":"<a class=\"btn btn-mini btn-success\" data-toggle=\"modal\" href=\"#?page=customers-database-edit&id=$1\">Edit<\/a>","3":"three"}

stdClass Object
(
    [1] => one
    [2] => <a class="btn btn-mini btn-success" data-toggle="modal" href="#?page=customers-database-edit&id=$1">Edit</a>
    [3] => three
)
like image 176
arkascha Avatar answered Dec 15 '25 08:12

arkascha