使用php将echo放入变量中
我遇到了一个函数的问题,该函数使用php函数使用php将echo放入变量中,php,variables,echo,Php,Variables,Echo,我遇到了一个函数的问题,该函数使用php函数fgetcsv()和echo从csv文件创建html 代码如下: <?php function getContent($data) { if (($handle = fopen($data, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { echo <p>...</p>
fgetcsv()
和echo
从csv文件创建html
代码如下:
<?php function getContent($data) {
if (($handle = fopen($data, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
echo <p>...</p>
}
}
} ?>
但它不起作用。。。有什么想法吗
附言:我在getContent函数中有很多echo
,这就是我不想使用变量的原因。(免责声明:我理解您当前的函数确实会回显您想要的内容,所以我假设您的回显行在本例中已修改,并且它包含一些带有$data
的真实内容,对吗?)
Echo打印到屏幕上,而您不希望这样,所以保存它并将其作为字符串返回。
快速示例:
function getContent($data) {
$result = ""; //you start with an empty string;
if (($handle = fopen($data, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$result .= "<p>...</p>"; //add what you used to echo to the string
}
}
return $result; //send your string back to the caller of the function
}
如果这样做有效,并且您可以将内容写入其中(显然必须定义$file
),您可以执行以下操作:
$content = getContent($data); //still gets you the data
fwrite($file, $content); //writes it to a file.
现在,如果写操作不起作用,您应该首先用硬编码的字符串调试它,但这与问题中的问题没有太多关系。我最终用一个变量
$text
更改了我的echo
,我像这样连接了$text.=“..”
之后,我只需要使用这个变量来创建html文件。您还没有定义文件指针
$file
我定义了,我只是将部分代码$data放在csv文件的名称中!我有“很多”关于getContent函数中的echo,我只显示了一行。如果我想使用$result,我必须将它连接起来,这不容易使用。不要太粗鲁,但那会带来坏运气。echo会将信息发送到屏幕上。你不想这样。你可以用内容缓冲和所有东西来做各种各样的技巧,但最终那只是黑客。你应该d将“从文件中获取信息”与“利用该信息做点什么”分开,这样您就可以在两个用例中重复使用您的功能,正如我所展示的。底线是,您当前的设计不支持您的新功能,因此需要进行重构。当然,需要做一些额外的工作,但最终会得到回报。下次您会记得从一开始就这样做。祝您好运
$content = getContent($data); //gets you the data in a string
echo $content; //echoes it, just like you did before.
$content = getContent($data); //still gets you the data
fwrite($file, $content); //writes it to a file.