如何在PHP中处理一个代码块,并将处理结果存储在变量中?

huangapple go评论52阅读模式
英文:

How do I process a block of code with proceed results stored in variable in php?

问题

我有一个 PHP 应用程序,在其中有一些代码片段,我想要处理并存储到一个变量中。它可能是包含 HTML 的数组数据的输出,我想要将其存储...

$myVar = { // 大括号表示开始存储

  foreach ($myarray as $key => $value) {
    echo '<td>' . $value . '</td>';
  }
} // 大括号表示结束存储

现在,该变量将包含完整的 echo 输出值。

是否有 PHP 函数、处理方法或推荐的方式可以实现这一目标。

我在这个项目中没有使用框架。

我正在寻找解决方案,因为我不知道正确的方法。

英文:

I have a php app where I have snippets of code that I want to process and store in a variable. It might be the output of array data with HTML that I want stored…

$myVar = { // bracket represents starting the store

  foreach ($myarray as $key =&gt; $value) {
    echo ‘&lt;td&gt;’ . $value . ‘&lt;/td&gt;’;
  }
}// close bracket represents end store

Now the variable would hold the value of what that full echo output would be.

Is there a php function, process, or recommend way of doing this.

I don’t have a framework I’m using on this project.

I am looking for a solution because I don’t know the right approach.

答案1

得分: 1

$myVar = '<td>' . implode('</td><td>', $myArray) . '</td>';

英文:

How about:

$myVar = &#39;&lt;td&gt;&#39; . implode(&#39;&lt;/td&gt;&lt;td&gt;&#39;, $myArray) . &#39;&lt;/td&gt;&#39;;

答案2

得分: 0

你可以使用ob_start和ob_get_clean函数将代码的输出存储到一个变量中:

ob_start();
foreach ($myarray as $key => $value) {
  echo '<td>' . $value . '</td>';
}
$myVar = ob_get_clean();

ob_start打开输出缓冲,它捕获脚本的所有输出并将其存储在缓冲区中。然后,ob_get_clean函数检索缓冲区的内容并丢弃它,最终将内容存储在$myVar变量中。

英文:

You can use the ob_start and ob_get_clean functions to store the output of the code in a variable:

    ob_start();
    foreach ($myarray as $key =&gt; $value) {
      echo ‘&lt;td&gt;’ . $value . ‘&lt;/td&gt;’;
    }
    $myVar = ob_get_clean();

ob_start turns on output buffering, which captures all output from your script and stores it in a buffer. The ob_get_clean function then retrieves the contents of the buffer and discards it, leaving you with the contents stored in the $myVar variable.

huangapple
  • 本文由 发表于 2023年2月6日 06:33:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355962.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定