【问题标题】:How do I include php within php?如何在 php 中包含 php?
【发布时间】:2014-02-01 20:20:26
【问题描述】:

我想包括:

<?php the_field('200_200_1', 'option'); ?>

在下一行的开始 div 标签之前...

$output .= '<div class="datebarcolor">'.$dates4.'</div>';

我不确定在这些情况下如何插入 php 标签。这是一个php文件,顺便说一句。

有人能指出正确的方向吗?

【问题讨论】:

  • 在您需要的时候尝试include 'your_file_path.php';。但在你的情况下,我不建议这样做。尝试了解模板化 - 使用 google。
  • 为什么PHP解释器运行时需要插入PHP标签?
  • @EdHeal 我认为关注点分离?!好像...
  • @MarkusHofmannn - 我假设 PHP 标记是 &lt;?php?我错了吗?

标签: php wordpress advanced-custom-fields


【解决方案1】:

如果您想包含一些其他 PHP 代码的输出(例如,如果 the_field 执行了一些 echo 调用)并且您想将其添加到 $output 变量中,请使用 ob_start 和 @987654325 @,就像这样:

ob_start();
the_field('200_200_1', 'option');
$output .= ob_get_clean(); //This appends everything to $output that was echoed since the call to ob_start
$output .= '<div class="datebarcolor">'.$dates4.'</div>';

【讨论】:

    【解决方案2】:

    如果您在 wordpress 中使用 ACF,您可以使用 get_field() 而不是 the_field(),以便将输出存储在您的 $output 变量中:

    $output .= get_field('200_200_1', 'option');
    $output .= '<div class="databarcolor">' . $date4 . '</div>';
    

    【讨论】:

    • 如果是这种情况,那么这是比通过输出缓冲更好的方法。编辑:显然是;)
    • @Krister 抱歉,有一个问题。如何将打开和关闭 div 标签添加到get_field();
    • @Desi - 可能是$output .= '&lt;div&gt;'.get_field('200_200_1', 'option').'&lt;/div&gt;'; 之类的东西?
    【解决方案3】:

    我认为你的意思是:

    在执行此代码之前包含文件:

    include 'yourfile.php';
    
    // ... some code ...
    $output .= '<div class="datebarcolor">'.$dates4.'</div>';
    

    或包含文件并将其输出添加到$output

    // start output buffer
    ob_start();
    include 'yourfile.php';
    
    // get buffer contents and clean the buffer
    $output .= ob_get_clean();
    
    $output .= '<div class="datebarcolor">'.$dates4.'</div>';
    

    【讨论】:

      猜你喜欢
      • 2012-08-10
      • 2011-03-29
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 2015-07-08
      • 2013-09-11
      • 2018-01-05
      • 2010-11-06
      相关资源
      最近更新 更多