【问题标题】:PHP: echo heredoc from another scriptPHP:从另一个脚本回显heredoc
【发布时间】:2012-12-16 05:29:36
【问题描述】:

我无法将heredoc 语句从一个 php 文件回显到另一个文件中。我有一个脚本用于检索 API 数据库信息,然后将该信息格式化为 heredoc 以将信息回显到 index.php 页面中。我的代码是:

while($artist_info = $artist_details_resource->fetch_assoc()){
   $artist = <<<DOC
             <img src="{$artist_info['image_url']}" alt="$artist_info['artist_name']" />
             <p>{$artist_name}</p>
DOC;
}

在 index.php 脚本中,我在我希望打印此 he​​redoc 的地方开始了一个 php 子句。代码是:

<?php
  if($artist){
     echo $artist;
  }
?>

但是,这只会打印 while 循环中的最后一个 heredoc 字符串,并且不会在每次迭代中回显每个 heredoc。

【问题讨论】:

  • 您是否尝试从同一个脚本打印它?
  • 是的,即使在同一个脚本上它只打印最后一个元素
  • 这个 herodoc 不是缺少结尾 DOC
  • 顺便说一句,你的结尾 DOC 在代码块之外

标签: php while-loop echo heredoc


【解决方案1】:

为什么会这样?您不是在循环中回显它,也不是在连接字符串。您在每次迭代时都会覆盖字符串。

while($artist_info = $artist_details_resource->fetch_assoc()){
   $artist .= <<<DOC
             <img src="{$artist_info['image_url']}" alt="$artist_info['artist_name']" />
             <p>{$artist_name}</p>
}

注意.=

【讨论】:

    【解决方案2】:

    当然这只会打印最后一个字符串,因为你使用$artist = &lt;&lt;&lt;DOC,所以你会在每个循环中覆盖 $artist 变量的值。

    试试$artist .= &lt;&lt;&lt;DOC或者放入数组:$artists[] = &lt;&lt;&lt;DOC

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多