0

我有这段代码可以将数据循环到我的网站:

$loop = Array();

# LOOP
foreach($sql->query($get_blogposts) AS $blogpost) {
    echo '<div class="blogpost-avatar" style="background-image: url('.url('images/avatars/avatar-cropped.jpg').');"></div>';

    echo '<div class="blogpost-information">';
        include(DIR_REQUIRED.'/blogpost-information.php');
    echo '</div>';

    echo '<div class="blogpost-content">';
        echo $blogpost['message'];
    echo '</div>';
}


echo implode('<hr>', $loop);

问题是我不知道如何$loop[] =进入foreach循环。我已经这样测试过:

    $loop[] = '<div class="blogpost-avatar" style="background-image: url('.url('images/avatars/avatar-cropped.jpg').');"></div>

    <div class="blogpost-information">'.
        include(DIR_REQUIRED.'/blogpost-information.php')
    .'</div>

    <div class="blogpost-content">'.
        $blogpost['message']
    .'</div>';

但我收到错误消息“打开失败......包含”。我什至测试过在=这样的前面添加一个点:$loop[] .=但这也不起作用。

我该如何解决我的问题?

提前致谢。

4

3 回答 3

3

使用输出缓冲区怎么样!

$loop = Array();    # LOOP
foreach($sql->query($get_blogposts) AS $blogpost) {
  $str = '';
  $str .= '<div class="blogpost-avatar" style="background-image: url('.url('images/avatars/avatar-cropped.jpg').');"></div>';

  $str .= '<div class="blogpost-information">';

  ob_start();

  include(DIR_REQUIRED.'/blogpost-information.php');
  $str .= ob_get_contents();
  ob_end_clean();

  $str .= '</div>';

  $str .= '<div class="blogpost-content">';
  $str .= $blogpost['message'];
  $str .= '</div>';
  $loop[] = $str;
}
于 2012-12-31T06:02:27.440 回答
0
<?php

$loop = array();

foreach ($sql->query($get_blogposts) as $blogpost) 
{
    ob_start();

        echo '<div class="blogpost-avatar" style="background-image: url('.url('images/avatars/avatar-cropped.jpg').');"></div>';
        echo '<div class="blogpost-information">';

        include DIR_REQUIRED.'/blogpost-information.php';

        echo '</div>';
        echo '<div class="blogpost-content">';
        echo $blogpost['message'];
        echo '</div>';

    $loop[] = ob_get_contents();
    ob_end_clean();
}

echo implode('<hr>', $loop);

?>

http://php.net/manual/en/function.ob-get-contents.php

于 2012-12-31T06:06:53.423 回答
0

我假设“blogpost-information.php”文件中存储了一些静态信息,因为您添加文件内容的方式,得出这个结论。如果我的猜测是正确的,那么以下解决方案可能会起作用 -

$str = "";
if(file_exists(DIR_REQUIRED.'/blogpost-information.php')){
  $str = fgets(DIR_REQUIRED.'/blogpost-information.php');
}
array_push($loop, "blah blah ".$str."blah blah ");

于 2012-12-31T06:09:06.023 回答