用php编写一个文件

用php编写一个文件,php,Php,此函数用于从数据库中获取记录。现在我想让它把它们写入一个文件。请帮帮我 function selectcsv($classname) { echo $sql = "SELECT * FROM tblstuden WHERE classname = $classname;"; $obj_db = new DB(); $obj_db->query($sql); while($row = $obj_db->rsse

此函数用于从数据库中获取记录。现在我想让它把它们写入一个文件。请帮帮我

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);
试试这个

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);
您从未将$out数据写入该文件

而不是:

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

fwrite($fh, $out);

您应该尝试阅读并理解。

您可以向该方法添加一个参数,然后使用输出缓冲创建要存储在文件中的内容,如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();
}
?>

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

那么问题是什么?代码创建了一个write.txt文件,但其中没有任何数据。我想要查看我的数据。应该写在一个文件中。这个$_POST[读取]不是应该吗;是$_POST['read'];?OP试图写入文件,而不是头。哦,我明白了,很抱歉。这段代码写的是文件,但需要下载。记住,当你得到问题的有用答案时,你应该接受答案,以感谢回答问题的人。你应该对你所有的问题都这样做,而不仅仅是这一个问题。在答案旁边的投票数下面寻找复选标记。您还可以查看本页了解更多信息:
$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);