Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write multiple variable using fwrite() in PHP? [closed]

I have a script that is writing variables to a text file, I am using fwrite(). here is the script:

<?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);


?>

I have 2 problems here:

1.As I receive the report by Batch_ID I want to name each report text file with a prefix using the batch_ID for example :5626_Report.txt

2.I want to pass more than one variable to the function fwrite(), I want to write the $status next to each $phone_number.


1 Answers

Try fprintf.

It's analogue to the regular printf of C, however you need to pass a handle to. As an example:

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

Alternatively, you can make use of PHPs inline stringing and use:

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

To get to your exact problem:

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

That should help.

like image 67
ATaylor Avatar answered Sep 13 '26 23:09

ATaylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!