Home >Backend Development >PHP Tutorial >How to write array variables to a file in PHP_PHP Tutorial
When using PHP to record logs, or when an Ajax request error occurs and you want to debug it. We generally write information to a specified file. Then deal with the problem based on the corresponding information.
For example, when I cannot get data using Ajax, I like to add the following code to the PHP script:
$fp=fopen('./a.txt','a+b'); fwrite($fp,$content); fclose($fp);
However, there is a problem. That is, what if $content is an array?
You might say, I loop the output. What if it’s a multidimensional array?
Do I need to work so hard just for debugging?
Here you can use var_export()
This function returns structural information about the variables passed to the function. It is similar to var_dump(), except that the representation returned is normal PHP code.
You can return a representation of a variable by setting the second parameter of the function to TRUE.
$fp=fopen('./a.txt','a+b'); fwrite($fp,var_export($content,true)); fclose($fp);
Note that the second parameter of var_export() needs to be set to true to obtain the return value. Otherwise, it is output directly.
In addition, if your $content is just an array and contains no other content, you can also use print_r(). Similarly, the second parameter of print_r() must also be set to true.
$fp=fopen('./a.txt','a+b'); fwrite($fp,print_r($content,true)); fclose($fp);