How to add HTML code to JSON in 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>

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
)

Need Your Help

Zend loader intel sense enabling

php zend-framework netbeans intellisense phpdoc

I have on many ocasions code which works with results from the client loader.

how to call an activity when getting incoming call.

android android-intent android-service android-input-method

Hi all i want to invoke a my own activity over the default incoming call activity.. i have done this with using broadcast receivers i am invoking my activity when getting incoming call. but it is w...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.