How to write array variables to files in PHP. How to write array variables to a file in PHP when logging in PHP, or when an Ajax request error occurs and you want to debug the file. We usually write information to a specified file. how does PHP write array variables to a file?
When logging with PHP, or Ajax request error, you want to debug. We usually write information to a specified file. Then the problem is handled according to the corresponding information.
For example, I like to add the following code in the PHP script when Ajax cannot retrieve data:
$fp=fopen('./a.txt','a+b');fwrite($fp,$content);fclose($fp);
However, there is a problem here. What if $ content is an array?
You may say that I loop the output. What about multi-dimensional arrays?
Is it so tiring for debugging.
Here you can use var_export ()
This function returns the structure information about the variables passed to this function. it is similar to var_dump (). The difference is that the returned representation is normal PHP code.
You can set the second parameter of the function to TRUE to return the expression of the variable.
$fp=fopen('./a.txt','a+b');fwrite($fp,var_export($content,true));fclose($fp);
Note that the second parameter of var_export () must be set to true to return the value. Otherwise, it is a direct output.
In addition, if your $ content is just an array and does not contain other content, you can also use print_r (), similarly, print_r () the second parameter must also be set to true.
$fp=fopen('./a.txt','a+b');fwrite($fp,print_r($content,true));fclose($fp);
Articles you may be interested in
- Introduction to array union, intersection, and difference set functions in php
- Php error_log () writes error messages to a file
- Differences between variables and functions in php after the static keyword is added
- Summary of methods for saving arrays as text formats in php
- PHP generates continuous numbers (letters) array function range () analysis, PHP lottery program function
- Summary of methods for removing duplicate values from a two-dimensional php array
- How to solve conflicts between concurrent read/write files in php
- Php method for obtaining the first array unit value of an array
When logging logs using PHP, or Ajax request error occurs, you want to debug the logs. We usually write information to a specified file...