我在使用带有 php 函数 fgetcsv()
和 echo
的 csv 文件创建 html 的函数时遇到了麻烦。
代码如下:
<?php function getContent($data) {
if (($handle = fopen($data, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
echo <p>...</p>
}
}
} ?>
它输出一个 html 表,然后,我想将其与函数一起使用 fwrite()
将其写入我刚刚创建的新 html 文件中。现在,我只是尝试将其用作这样的变量:
$content = getContent($data);
fwrite($file, $content);
但它不起作用...知道吗?
PS:我在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
}
现在你可以调用该函数并对字符串执行操作。首先,使用 echo
进行测试:
$content = getContent($data); //gets you the data in a string
echo $content; //echoes it, just like you did before.
如果这有效,并且您有一些内容可以写入(必须明确定义$file
,则可以执行所做的事情:
$content = getContent($data); //still gets you the data
fwrite($file, $content); //writes it to a file.
现在,如果写入不起作用,您应该首先使用硬编码的字符串进行调试,但这与此问题中的问题没有太大关系。
我最终用一个变量$text
改变了我的echo
,我像这样连接$text .= "<p>...</p>"
之后,我只需要使用此变量来创建 html 文件。