Reputation: 9956
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&M
Upvotes: 1
Views: 3462
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 &
. From source code:
$url .= '&' . http_build_query($args);
I ended
str_replace('&','&',$this->url->link('product/product', 'product_id=1'))
Upvotes: 0
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 & => &
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 &
var asHtml = $('#bootstrap').html();
console.log(asHtml);
// uses &
var asText = $('#bootstrap').text();
console.log(asText);
});
Upvotes: 0
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(/&/g, "\&");
};
console.log(convertAmpersand(titles[0]));
Upvotes: 2