I am using an Advanced Custom Fields repeater to dynamically create a list of locations to be placed on a Google map. I am trying to convert my PHP array to JSON so that I can access the locations in my Google Maps script file. The issue I am running into is that locations with an apostrophe are causing an error in the Javascript. I know that the apostrophes need to be escaped, but I am not sure how to do it dynamically.
Here is my PHP:
$locations = get_field('locations');
$jsonLocations = json_encode($locations);
Then I am trying to pass the PHP array to Javascript like so:
var jsonLocations = '<?php echo $jsonLocations; ?>';
This is what's causing me the problem. I tried using utf8_encode
based on another question I found on here, but that gave me a null
result.
$locations = get_field('locations');
$jsonLocations = utf8_encode($locations);
$jsonLocations = json_encode($jsonLocations);