英文:
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 => $value) {
echo ‘<td>’ . $value . ‘</td>’;
}
}// 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 = '<td>' . implode('</td><td>', $myArray) . '</td>';
答案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 => $value) {
echo ‘<td>’ . $value . ‘</td>’;
}
$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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论