Finglish
Finglish

Reputation: 9956

why do ampersands become html codes when converting with php json_encode

I have an array in php that I am parsing to a javascript. My problem is that some of the strings in the array contain ampersands, and they become & instead of & in the javascript. Here is a simple example to illustrate my issue:

<? $titles = json_encode(array("H&M", "Tesco")); ?>

<script>
var titles = <? echo $titles; ?>; 
console.log(titles[0]);
</script>

the log reads:

H&amp;M

Upvotes: 1

Views: 3462

Answers (3)

Hebe
Hebe

Reputation: 810

I had a similar issue in opencart.

$json = array(
   'href' => $this->url->link('product/product', 'product_id=1'),
);
echo json_encode($json);

It occured that link function was deliberately creating &amp;. From source code:

$url .= '&amp;' . http_build_query($args);

I ended

str_replace('&amp;','&',$this->url->link('product/product', 'product_id=1'))

Upvotes: 0

csum
csum

Reputation: 2027

In case this helps others, I was doing something similar to your example, but using jQuery to read a JSON string that I had injected into an HTML element.

As mentioned in some of the comments, PHP was not doing the & => &amp; encoding. It was being done in javascript. The solution was to use jQuery's .text() instead of .html():

PHP:

<div id="bootstrap"><?= json_encode(array("H&M", "Tesco")) ?></div>

Javascript:

$(function () {
  // uses &amp;
  var asHtml = $('#bootstrap').html();
  console.log(asHtml);

  // uses &
  var asText = $('#bootstrap').text();
  console.log(asText);
});

Upvotes: 0

aecend
aecend

Reputation: 2462

It happens because that's how the HTTP protocol divides the elements of a GET or POST transaction. This will solve the problem on the javascript end:

var convertAmpersand = function(str) {
  return str.replace(/&amp;/g, "\&");
};

console.log(convertAmpersand(titles[0]));

Upvotes: 2

Related Questions