How to Print & Write Array to File Output in PHP

»»»How to Print & Write Array to File Output in PHP
When outputting the content data of array to a file in PHP, simply pass the data variable of array type to file_put_content() or fwrite() function to write the data to the file may not return the desired result. Instead of human-readable information of the array that shows shows types or keys and elements, only the word “Array” is written to the file.

When displaying to screen or presentation media, programmer normally uses print_r() function to display the complete data of the array in a way that’s readable by humans.

In order to write the content and data of array to the file, we can use the print_r() or var_export() functions to return the output instead of printing it.

For example for the syntax,

$array_content = print_r($array, TRUE);

Or,

$array_content = var_export($array, TRUE);
Note
“TRUE” in the print_r() function is for “return” parameter that instructs the function to return the information rather than print it.

It’s possible to directly return the results when writing to file:

file_put_contents('filename.txt', print_r($array, TRUE));

Or,

file_put_contents('filename.txt', var_export($array, TRUE));

By | 2017-01-16T22:20:01+00:00 January 16th, 2017|Categories: Developer Tools|Tags: , |0 Comments

About the Author:

LK is a technology writer for Tech Journey with background of system and network administrator. He has be documenting his experiences in digital and technology world for over 15 years.Connect with LK through Tech Journey on Facebook, Twitter or Google+.

Pin It on Pinterest

Share This

Share This

Share this post with your friends!