vorandasb
vorandasb

Reputation: 23

How to write to a text file using array's?

Im struggling to make the 2 array's write to a text file. How could I fix the code to get it going? Do I have to use 'echo implode' making the array's into a conversion? Thank you

$rainf_array = array($rainf0, $rainf1, $rainf2, $rainf3, $rainf4, $rainf5, $rainf6 ); 
 
$date_array = array($date0, $date1, $date2, $date3, $date4, $date5, $date6 );
 
   //Input value are saved to the file 
    { 
     $fileHandle = fopen($fileName, "w");

     fwrite($fileHandle, $date_array . ' ' . $rainf_array ."\n" );   
        
     fclose($fileHandle);

Upvotes: 0

Views: 35

Answers (2)

Manash Kumar
Manash Kumar

Reputation: 1085

You can't write array directly to file. Either you have to use serialize() or json_encode() to make it string.

fwrite($fileHandle, json_encode($date_array) . ' ' . json_encode($rainf_array) ."\n" );   

OR

fwrite($fileHandle, serialize($date_array) . ' ' . serialize($rainf_array) ."\n" );  

Upvotes: 1

ezio4df
ezio4df

Reputation: 4105

why dont you encode to json, like this,

$arr = [
  'date' => $date_array,
  'rainf' => $rainf_array,
];

fwrite($fileHandle, json_encode($arr));   

see https://www.php.net/function.json-encode

Upvotes: 1

Related Questions