According to the HTML5 specification for <iframe>
, we need to replace the quotes and ampersands in the srcdoc string with HTML entities:
In the HTML syntax, authors need only remember to use """ (U+0022) characters to wrap the attribute contents and then to escape all """ (U+0022) and U+0026 AMPERSAND (&) characters, and to specify the sandbox attribute, to ensure safe embedding of content.
Notice the way that quotes have to be escaped (otherwise the srcdoc attribute would end prematurely), and the way raw ampersands (e.g. in URLs or in prose) mentioned in the sandboxed content have to be doubly escaped — once so that the ampersand is preserved when originally parsing the srcdoc attribute, and once more to prevent the ampersand from being misinterpreted when parsing the sandboxed content.
We can achieve this in PHP using str_replace()
:
$srcdoc = '<div id="foo">"Contains quoted text."</div>';
$escaped = str_replace([ '"', '&' ], [ '"', '&amp;' ], $srcdoc);
The ampersand replacement shown above is not a typo. This code produces:
<div id="foo">"Contains quoted text."</div>
Then, we can use the escaped value for the srcdoc
attribute value:
<div id="email_content">
<iframe sandbox srcdoc="<div id="foo">"Contains quoted text."</div>"></iframe>
</div>
Note that the HTML5 srcdoc feature is not available in Internet Explorer. Edge supports srcdoc as of version 79 (January 2020). Support in email clients will be even lower.