Parse PHP how to write array variables to a file

  • 2020-06-07 04:05:27
  • OfStack

When logging with PHP, or when Ajax requests an error and wants debug. We usually write the information to a specified file
In the middle. Then deal with the problem according to the corresponding information.
For example, I like to add the following code to the PHP script when I can't get data with Ajax

$fp = fopen('./a.txt', 'a+b'); 
fwrite($fp, $content); 
fclose($fp); 

But there is one problem. So what if $content is 1 array?
You might say, I'm looping the output. What about multidimensional arrays?
I'm just getting so tired for debug.
Here you can use var_export().
This function returns structural information about the variable passed to the function, which is similar to var_dump() except that
The returned representation is the valid PHP code.
You can return a representation of a variable by setting the second argument 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 indicate a return value. Or direct output
Also, if your $content is just an array and contains nothing else
You can also use print_r()
Similarly, the second parameter of print_r() is also set to true

$fp = fopen('./a.txt', 'a+b');
fwrite($fp, print_r($content, true));
fclose($fp);

Related articles: