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":"&lt;img src=&quot;http:\/\/mysite.com\/image.jpg&quot;&gt;","string":"some string"}'></tag>