I'm using php's tidy library to "clean and repair" some html coming from user input.
Everything works fine, but i'm running into a problem that I can't figure out what its cause is. My code is like this:
$tidy = new tidy();
$tidy_options = array(
'hide-comments' => true,'tidy-mark' => false, 'indent' => false,
'new-blocklevel-tags' => 'article,footer,header,hgroup,output,progress,section,video',
'new-inline-tags' => 'audio,details,time,ruby,rt,rp',
'drop-empty-paras' => false,
'doctype' => '<!DOCTYPE HTML>',
'sort-attributes' => 'none', 'vertical-space' => false,
'output-xhtml' => true,'wrap' => 180,
'wrap-attributes' => false,
'break-before-br' => false,
'show-body-only' => true
);
$data = $tidy->repairString($data, $tidy_options, 'UTF8');
echo $data;
This works for all kinds of input, except when i'm trying to use html for embeding swf files.
So , i try this code:
<object data="http://the_swf_file_url" type="application/x-shockwave-flash" width="853" height="520">
<param name="movie" value="http://the_swf_file_url">
</object>
but repairString stripes off all of it, and returns an empty string.
The strangest thing is that:
-If i enter some text along with the above, so the input is like Hello world<object...>...</object>
then it works fine.
-Or if i specify 'show-body-only' => false
it also works fine!
Any clue Why this is happening? Thanks in advance.
Edit: tried pankar's suggestion with setting preserve-entities to true but had no luck...
The problem is that you are trying to process an HTML fragment.
When you do this, the rest of the document is inferred. If you leave the configuration as default, and output a tidy document with just a piece of text, you will see the DOCTYPE
, html
, head
and body
tags that you did not give it. It inferred that these tags had to exist.
The problem here is that the HTML specification regarding objects states that:
The OBJECT element may also appear in the content of the HEAD element.
When the location of your fragment is being inferred, it puts it in the first place that it can occur. This means that tidy will place it in the head
tag.
The reason why show-body-only
is affecting your output is because your fragment did not get placed in the body
.
body
tag. This is because raw text is not allowed in the head
tag. So the logically inferred location of your fragment is in the body
.
In my opinion, the best option available to you is to inject all of your code fragments into a "template" document, and then parse them out again afterwards. You can probably do this fairly easily with DOMDocument
.
A second solution would be to inject a sentinel value that you can strip out again afterwards, when showing only the body.
I.e.
____MY_MAGIC_TOKEN____
<object ...></object>
Then you can strip it out again afterwards.