Home  >  Article  >  Backend Development  >  How to write an array to a file in php (three methods)

How to write an array to a file in php (three methods)

PHPz
PHPzOriginal
2023-04-20 15:07:272291browse

In PHP, you can use the following methods to write an array to a file:

Method 1: Use the fwrite() function

In this method, we first need to open the file , and then use the fwrite() function to write the array to the file. Below is a sample code where we open a file named "data.txt" and write an array named "my_data" into it:

<?php
$my_data = array("Apple","Banana","Orange");

$file = fopen("data.txt","w");
if($file)
{
  fwrite($file,serialize($my_data));
  fclose($file);
}
?>

In the above code, we first define An array named "my_data" is created, and then we open a file named "data.txt". If the file is opened successfully, we convert the array to a string using PHP's serialize() function and write it to the file using the fwrite() function. Finally, we close the file.

Method 2: Using file_put_contents() function

In this method, we can easily write the entire array to a file using PHP’s file_put_contents() function. Here is a sample code:

<?php
$my_data = array("Apple","Banana","Orange");
file_put_contents("data.txt",serialize($my_data));
?>

In the above code, we first define an array named "my_data". We then write the entire array to a file using the file_put_contents() function. The first parameter of this function is the file name, and the second parameter is the data to be written.

Method 3: Use json_encode() function

In this method, we can use PHP's json_encode() function to convert the array into JSON format and write it to a file. Here is a sample code:

<?php
$my_data = array("Apple","Banana","Orange");
file_put_contents("data.txt", json_encode($my_data));
?>

In the above sample code, we first define an array named "my_data". We then convert the array to a JSON string using the json_encode() function and write it to a file using the file_put_contents() function.

Summary

In this article, we introduced three methods of writing arrays to files in PHP. These methods include using the fwrite() function, file_put_contents() function and json_encode() function. You can choose one of the methods according to your needs. I hope this article helped you learn how to write an array to a file.

The above is the detailed content of How to write an array to a file in php (three methods). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn