如何在php中正确使用fwrite和while函数

如何在php中正确使用fwrite和while函数,php,while-loop,fwrite,Php,While Loop,Fwrite,以下是我创建另一个文件的php代码: $title = $_POST['title']; $location = $_POST['location']; $category = $_POST['category']; $b = './'.$title.".html"; $a = fopen("$b", "w"); fwrite($a, $title); fwrite($a, $location); fwrite($a, $category); fclose($a); 这里只有几行变量,

以下是我创建另一个文件的php代码:

$title = $_POST['title'];
$location = $_POST['location'];
$category = $_POST['category'];

$b = './'.$title.".html";

$a = fopen("$b", "w");

fwrite($a, $title);
fwrite($a, $location);
fwrite($a, $category);

fclose($a);
这里只有几行变量,我还有更多的变量需要编写。 我的问题是如何有效地使用while函数,这样我就不需要重复写这么多次,或者请教我一个更好的方法来完成这项工作

提前Thx

只是一个建议, 您可以将行添加到数组中,并以这种方式添加,例如:

$file = fopen('file.txt', 'w');
foreach ($yourValues as $lines)
{
    fwrite($file, $lines->getAttribute('id') . "\n");
}

将所有变量发布到数组中,如下所示:

$vararr[] = $_POST['title'];
$vararr[] = $_POST['location'];

foreach($vararr as $data){
   fwrite($a, $data);
}

您可以在数组中获取所有表单值一次,然后在其中循环

    $data = array();
    foreach($POST as $key => $value){
      $data[$key] = $value;
    }

    foreach($data as $key => $line){
    $string = "$key = $line";
    fwrite($a, $string);
    }

您必须读入所有行并创建一个数组。之后,您可以简单地将这些行再次写入另一个文件

$file = fopen('file.txt', 'w');

foreach ($yourLines as $lines)
{
    fwrite($file, $lines->getAttribute('id') . "\n");
}