Question

I'm trying to figure out how to make $obj->setAttribute() use single quotes when setting the attribute, so that I can place a JSON array inside.

Here's the basics of what I'm trying to accomplish.

$code = '<img src="http://example.com/image.jpg">';

$array = array(
  'code' => htmlspecialchars($code),
  'string' => $string
);

$tag->setAttribute('data-stuff', json_encode($array));

Now that's all good and well, but the JSON uses double quotes, and the new tag also uses double quotes.

<tag data-stuff="{"code":"&lt;img src=&quot;http://example.com/image.jpg&quot;&gt;","string":"some string"}">

This is an issue, since the attribute needs to be using single quotes so it doesn't interfere with the JSON's double quotes. Further complicated by the fact that the JSON contains contains HTML converted to special chars. So if I were to convert the JSON to special chars, then when I try to decode it 'code' will be also decoded which can cause all sorts of problems when trying to grab it with JavaScript.

Does anyone know of a clean way in which I can convert the surrounding 'data-stuff' attribute's container tags to single characters? I'd much prefer that option than escaping the json quotes.

Was it helpful?

Solution

You can try the saveHTML() method:

<?php

$code = '<img src="http://mysite.com/image.jpg">';
$array = array(
  'code' => htmlspecialchars($code),
  'string' => 'some string',
);

$doc = new DomDocument;
$tag = $doc->createElement("tag");
$tag->setAttribute('data-stuff', json_encode($array));
echo $doc->saveHTML($tag);

... which produces:

<tag data-stuff='{"code":"&amp;lt;img src=&amp;quot;http:\/\/mysite.com\/image.jpg&amp;quot;&amp;gt;","string":"some string"}'></tag>

OTHER TIPS

(Posted answer on behalf of the question author).

Never mind, I've fixed it. I was viewing the code inside the browser, when I output it as a string it's showing up as single quotes, browser is just displaying double quotes in the view source.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top