tags:

views:

144

answers:

2

How can I set my Iframe height to be dynamic to its content.

The content is only PHP code, nothing else.

I use the php to query database, and then show some ads. The more ads, the higher the iframe should be.

I thought height='100%' should do it, but no...

I have read other Q but their solutions doesn't work for me.

Suggestions ?

Thanks

A: 

If the ads are just text, you can use line height * number of lines as the height. I assume you know the font size, and number of lines can be found by counting <br />'s:

<?php
// $content is your ads
// assuming ads.php returns an ad with an id, this example uses ad #10
// We are reading it with a full url because we don't want to read it as just
// a text file (we want it to be interpreted by php before we load it)
$content = file_get_contents('http://www.example.com/ads.php?id=10');
$line_height = 12; // line-height: 12px; is set in CSS
$number_of_lines = substr_count($content,'<br />'); // you can search for <br>
                                                    // and <br/> as well if you 
                                                    // need to
$height = $line_height * $number_of_lines; // You may also want to have padding

?>
<iframe src="ads.php?id=10" height="<?php echo $height; ?>" />

EDIT: changed $font_size to $line_height

Brendan Long
Also this much easier if it's just images of the same height: $height = $image_height * $number_of_images;
Brendan Long
Oh, and you can count images with substr_count($content, '<img');
Brendan Long
+1  A: 

You have to set height of iframe in javascript. JavaScript should be in page inside the iframe (must be if page with iframe and page in iframe are from different domains).

a.html:

<iframe src="b.html" id="myiframe"></iframe>

b.html:

<div style="height: 500px; background:magenta;"></div>
<script>
    parent.document.getElementById('myiframe').style.height = document.body.offsetHeight+'px';
</script>
Kamil Szot
This doesn't work cross domains.
Frederico