Re: include as string
- From: Jerry Stuckle <jstucklex@xxxxxxxxxxxxx>
- Date: Tue, 08 Apr 2008 13:08:47 -0400
Harris Kosmidhs wrote:
Hello,
I have a php file like the following:
<?php foreach($res as $album) { ?>
<div class="albums">
<div class="left albumimage">
<a href="album/<?php echo $album["id"] ;?>">
<img alt="<?php echo $album["title"]; ?>" title="<?php echo $album["title"]; ?>" src="<?php echo "../".$photosdir.$album["photo"]; ?>">
</a>
</div>
<?php } ?>
I call this file from a function :
function ListAlbums($res) {
include('views/albums_view.php');
}
Before this I have opened a sql query and $res has the resultset. So my pages renders correctlly for each of the rows on $res.
But now I want for this file not to be printed directly (as include does) but rather store the output to a string. As I read at http://us3.php.net/include/ I did:
function ListAlbums($res) {
ob_start();
include('views/albums_view.php');
$disp=ob_get_contents();
ob_end_clean();
return $disp;
}
But $res now seems to be empty. Why doesn't this approach work? If I print_r($res) into my function it returns of course data.
thanks
I'm not sure why it shouldn't work. However, there is a better way to do this.
First of all, the code in your included file should itself be a function. Then, rather than outputting the html right there, put it into a string, and return the string, i.e.
<?php
function myfunc($res, $photosdir) {
$str = '';
foreach($res as $album) {
$str .= <<<EOT
<div class="albums">
<div class="left albumimage">
<a href="album/{$album["id"]}">
<img alt="{$album["title"]}" title="{$album["title"]}"
src="../{$photosdir}{$album["photo"]}">
</a>
</div>
EOT;
}
return $str;
}
Now in the calling routine you have the option of echoing the string or not, i.e.
echo $myfunc($res, $photosdir);
or
$str = $myfunc($res, $photosdir);
You can now include the file at the top of your page and call it from where ever you need it.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@xxxxxxxxxxxxx
==================
.
- References:
- include as string
- From: Harris Kosmidhs
- include as string
- Prev by Date: Re: Are you a GoDaddy user?
- Next by Date: Re: Help
- Previous by thread: Re: include as string
- Next by thread: (http://nike-jordan.photo.163.com) is the biggest wholesales Jordan 1-23 outlet shoes in China , Cheap wholesale men Jordan shoes, women Jordan shoes , kids Jordan shoes, cheap wholesale Jordan 1, 2 , 2 1/2 , 3 , 3 1/2 , 4 , 5 , 6, 7, 7 1/2, 8 , 9 , 9 1/2,10,.11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 21 1/2, 22, 23 outlet shoes and JordanFusion shoes( J3+AF1, J4+AF1, J5+AF1,J10+J12, J12+AF1, J23+AF1) , whoesale Jordan big size us 14, size us 15..
- Index(es):
Relevant Pages
|