Generating json, how do I escape double quotes?

Hi,

I’m generating some json for SEO in the header. But running into issues if there are quotes in the title. For example:

"name": "<?= $page->title() ?>",

If the title is: This is a “great” title

The json would be:

{
  "name": "This is a "great" title",
}

Thus, an invalid json.

Any ideas?

You would have to escape the quotes, but if I were you, I’d create an array and then json_encode() it, which will result in much cleaner code and do the escaping for you:

  $data = [
    'name' => $page->title(),
  ];

  echo json_encode($data);

Result:

 {"name":"This is a \"great\" title"}
1 Like

Sweet!!