0

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.

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

3 Comments

That's what I already do, I didn't post the full markup. However according to my browser it's showing up with double quotes not single quotes.
I didn't even use a browser to test. Make sure you are seeing the actual script's output (and not, e.g., as shown in Firebug's "HTML" panel).
Yeah I did that just a minute ago, I'm just being an idiot. It was just the browser making it appear as though it's double quotes. Good hour of my day wasted. Thanks man.
0

(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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.