0

此函数从数据库中获取记录。现在我希望它把它们写到一个文件中。请帮我。

function selectcsv($classname)
    {
        echo $sql = "SELECT * FROM tblstuden WHERE classname = $classname;"; 
        $obj_db = new DB();
        $obj_db->query($sql);

        while($row = $obj_db->rsset()){
        $this->_id($row[id]);
        $this->_studentname($row[studentname]);
        $this->_rollnumber($row[rollnumber]);
        $this->_classname($row[classname]);

        $out = $out . $row[studentname] . " , ". $row[rollnumber] . "\n";
        }

        $obj_db->db_close();

以上部分正在运行

$myFile = "write.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "write::";
fwrite($fh, $stringData);
$stringData = $_POST[read];
fwrite($fh, $stringData);
fclose($fh);
4

4 回答 4

0

您可以向该方法添加一个参数,然后使用输出缓冲来创建要存储在您的文件中的内容,因为ob_clean();使用它不会被输出,但您仍然有您$out想要从该方法返回的情况:

<?php 
function selectcsv($classname,$writeFile=true)
{
    echo $sql = "SELECT * FROM tblstuden WHERE classname = $classname;";
    $obj_db = new DB();
    $obj_db->query($sql);

    if($writeFile==true){ob_start();}

    while($row = $obj_db->rsset()){
        $this->_id($row['id']);
        $this->_studentname($row['studentname']);
        $this->_rollnumber($row['rollnumber']);
        $this->_classname($row['classname']);
        if($writeFile==true){
            echo $row['studentname'] . " , ". $row['rollnumber'] . PHP_EOL;
        }
        $out .= $row['studentname'] . " , ". $row['rollnumber'] . PHP_EOL;
    }

    if($writeFile==true){
       $tofile = ob_get_contents();
       ob_clean();
       file_put_contents($classname.'.csv',$tofile);
    }

    return $out;
    $obj_db->db_close();
}
?>
于 2012-06-05T06:48:17.063 回答
0
$myFile = "write.txt";
$fh = fopen($myFile, 'w') or die("can't open file");

$stringData = "write::";
fwrite($fh, $stringData);

$stringData = $_POST['read'];
if(isempty($stringData){echo 'Nothing to write';}
else
fwrite($fh, $stringData);

fclose($fh);

我认为数组索引字符串应该用引号括起来,而且,您可以检查 POST 数组是否包含有效数据

于 2012-06-05T06:48:41.600 回答
0

来试试这个,

header("Content-type: application/octet-stream");
header("Content-disposition:attachment; filename=".$myFile);

echo $out;

在你的情况下:

$myFile = "write.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $out;
fwrite($fh, $stringData);
$stringData = $_POST['read'];
fwrite($fh, $stringData);
fclose($fh);
于 2012-06-05T06:32:36.357 回答
0

您永远不会将$out数据写入文件。

代替:

$stringData = "write::";
fwrite($fh, $stringData);
$stringData = $_POST[read];
fwrite($fh, $stringData);

你应该:

fwrite($fh, $out);

您应该尝试阅读并理解fwrite 的 PHP 手册页

于 2012-06-05T06:44:44.293 回答