【问题标题】:How to write multiple variable using fwrite() in PHP? [closed]如何在 PHP 中使用 fwrite() 编写多个变量? [关闭]
【发布时间】:2012-10-31 21:11:13
【问题描述】:

我有一个将变量写入文本文件的脚本,我正在使用 fwrite()。这是脚本:

<?php

error_reporting(E_ALL ^ E_NOTICE);

$filename = 'Report.txt';


$batch_id = $_GET['batch_id'];
$status = $_GET['status'];
$phone_number = $_GET['phone_number'];

//check to see if I could open the report.txt
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    // I am trying to write each variables to the text file
    if (fwrite($handle, $phone_number) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($phone_number) to file ($filename)";

    fclose($handle);


?>

我有两个问题:

1.当我通过 Batch_ID 收到报告时,我想使用 batch_ID 为每个报告文本文件命名,并带有前缀,例如:5626_Report.txt

2.我想将多个变量传递给函数fwrite(),我想在每个$phone_number 旁边写下$status。

【问题讨论】:

  • 不知道什么并不可耻。寻求帮助也没有什么可耻的。然而,甚至没有尝试并期望其他人为您解决问题是可耻的。我认为您没有在这里这样做,因此我认为没有理由否决您的问题。

标签: php variables text


【解决方案1】:

试试 fprintf。

它类似于 C 的常规 printf,但是您需要将句柄传递给。 举个例子:

fprintf($handle, "%s;%s;%s", $batch_id, $status, $phone_number);

或者,您可以使用 PHP 内联字符串并使用:

fwrite($handle "$batch_id;$status;$phone_number");

要解决您的确切问题:

$filename = $batch_id."_report.txt";
$handle = fopen($filename, "a");
fwrite($handle, "$phone_number $status");

这应该会有所帮助。

【讨论】:

  • 感谢您的回复,这解决了我的一半问题但是当文件被创建时,名称是 _report ,前缀不显示
  • 为此,您需要确保实际设置了 $batch_id。使用 '$batch_id = (isset($_GET['batch_id']) ? $_GET['batch_id'] : "12345";' 如果未设置 batch_id,这将在 report.txt 前添加默认值 '12345' .
【解决方案2】:

你可以做的更简单:

$status = $_GET['status'];
$phone_number = $_GET['phone_number'];

$file = $_GET['batch_id']."_Report.txt";
//place here whatever you need
$content = "Some content".$status."\n";
file_put_contents($file, $current);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2020-01-05
    相关资源
    最近更新 更多