phpjsondomquotessetattribute

Putting JSON into HTML attribute using PHP's setAttribute, double quote issue


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.


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>