1

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);
user13286
  • 2,822
  • 8
  • 40
  • 83

1 Answers1

2

JSON_HEX_QUOT, JSON_HEX_APOS

http://php.net/manual/en/function.json-encode.php

chris85
  • 23,591
  • 7
  • 30
  • 47
bassxzero
  • 4,605
  • 20
  • 34