Print array to a file
PhpSerializationPhp Problem Overview
I would like to print an array to a file.
I would like the file to look exactly similar like how a code like this looks.
print_r ($abc);
assuming $abc is an array.
Is there any one lines solution for this rather than regular for each look.
P.S - I currently use serialize but i want to make the files readable as readability is quite hard with serialized arrays.
Php Solutions
Solution 1 - Php
Either var_export
or set print_r
to return the output instead of printing it.
$b = array (
'm' => 'monkey',
'foo' => 'bar',
'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results now contains output from print_r
You can then save $results
with file_put_contents
. Or return it directly when writing to file:
file_put_contents('filename.txt', print_r($b, true));
Solution 2 - Php
Just use print_r
; ) Read the documentation:
> If you would like to capture the output of print_r()
, use the return
parameter. When this parameter is set to TRUE
, print_r()
will return the information rather than print it.
So this is one possibility:
$fp = fopen('file.txt', 'w');
fwrite($fp, print_r($array, TRUE));
fclose($fp);
Solution 3 - Php
You could try:
$h = fopen('filename.txt', 'r+');
fwrite($h, var_export($your_array, true));
Solution 4 - Php
file_put_contents($file, print_r($array, true), FILE_APPEND)
Solution 5 - Php
Quick and simple do this:
file_put_contents($filename, var_export($myArray, true));
Solution 6 - Php
You can try this, $myArray
as the Array
$filename = "mylog.txt";
$text = "";
foreach($myArray as $key => $value)
{
$text .= $key." : ".$value."\n";
}
$fh = fopen($filename, "w") or die("Could not open log file.");
fwrite($fh, $text) or die("Could not write file!");
fclose($fh);
Solution 7 - Php
However op needs to write array as it is on file I have landed this page to find out a solution where I can write a array to file and than can easily read later using php again.
I have found solution my self by using json_encode so anyone else is looking for the same here is the code:
file_put_contents('array.tmp', json_encode($array));
than read
$array = file_get_contents('array.tmp');
$array = json_decode($array,true);
Solution 8 - Php
I just wrote this function to output an array as text:
Should output nicely formatted array.
IMPORTANT NOTE:
Beware of user input.
This script was created for internal use.
If you intend to use this for public use you will need to add some additional data validation to prevent script injection.
This is not fool proof and should be used with trusted data only.
The following function will output something like:
$var = array(
'primarykey' => array(
'test' => array(
'var' => array(
1 => 99,
2 => 500,
),
),
'abc' => 'd',
),
);
here is the function (note: function is currently formatted for oop implementation.)
public function outArray($array, $lvl=0){
$sub = $lvl+1;
$return = "";
if($lvl==null){
$return = "\t\$var = array(\n";
}
foreach($array as $key => $mixed){
$key = trim($key);
if(!is_array($mixed)){
$mixed = trim($mixed);
}
if(empty($key) && empty($mixed)){continue;}
if(!is_numeric($key) && !empty($key)){
if($key == "[]"){
$key = null;
} else {
$key = "'".addslashes($key)."'";
}
}
if($mixed === null){
$mixed = 'null';
} elseif($mixed === false){
$mixed = 'false';
} elseif($mixed === true){
$mixed = 'true';
} elseif($mixed === ""){
$mixed = "''";
}
//CONVERT STRINGS 'true', 'false' and 'null' TO true, false and null
//uncomment if needed
//elseif(!is_numeric($mixed) && !is_array($mixed) && !empty($mixed)){
// if($mixed != 'false' && $mixed != 'true' && $mixed != 'null'){
// $mixed = "'".addslashes($mixed)."'";
// }
//}
if(is_array($mixed)){
if($key !== null){
$return .= "\t".str_repeat("\t", $sub)."$key => array(\n";
$return .= $this->outArray($mixed, $sub);
$return .= "\t".str_repeat("\t", $sub)."),\n";
} else {
$return .= "\t".str_repeat("\t", $sub)."array(\n";
$return .= $this->outArray($mixed, $sub);
$return .= "\t".str_repeat("\t", $sub)."),\n";
}
} else {
if($key !== null){
$return .= "\t".str_repeat("\t", $sub)."$key => $mixed,\n";
} else {
$return .= "\t".str_repeat("\t", $sub).$mixed.",\n";
}
}
}
if($lvl==null){
$return .= "\t);\n";
}
return $return;
}
Alternately you can use this script I also wrote a while ago:
This one is nice to copy and paste parts of an array.
( Would be near impossible to do that with serialized output )
Not the cleanest function but it gets the job done.
This one will output as follows:
$array['key']['key2'] = 'value';
$array['key']['key3'] = 'value2';
$array['x'] = 7;
$array['y']['z'] = 'abc';
Also take care for user input. Here is the code.
public static function prArray($array, $path=false, $top=true) {
$data = "";
$delimiter = "~~|~~";
$p = null;
if(is_array($array)){
foreach($array as $key => $a){
if(!is_array($a) || empty($a)){
if(is_array($a)){
$data .= $path."['{$key}'] = array();".$delimiter;
} else {
$data .= $path."['{$key}'] = \"".htmlentities(addslashes($a))."\";".$delimiter;
}
} else {
$data .= self::prArray($a, $path."['{$key}']", false);
}
}
}
if($top){
$return = "";
foreach(explode($delimiter, $data) as $value){
if(!empty($value)){
$return .= '$array'.$value."<br>";
}
};
echo $return;
}
return $data;
}
Solution 9 - Php
Here is what I learned in last 17 hours which solved my problem while searching for a similar solution.
resources:
http://php.net/manual/en/language.types.array.php
Specific Code :
// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]"; // Hello apple
What I took from above, $arr[fruit] can go inside " " (double quotes) and be accepted as string by PHP for further processing.
Second Resource is the code in one of the answers above:
file_put_contents($file, print_r($array, true), FILE_APPEND)
This is the second thing I didn't knew, FILE_APPEND.
What I was trying to achieve is get contents from a file, edit desired data and update the file with new data but after deleting old data.
Now I only need to know how to delete data from file before adding updated data.
About other solutions:
Just so that it may be helpful to other people; when I tried var_export or Print_r or Serialize or Json.Encode, I either got special characters like => or ; or ' or [] in the file or some kind of error. Tried too many things to remember all errors. So if someone may want to try them again (may have different scenario than mine), they may expect errors.
About reading file, editing and updating:
I used fgets() function to load file array into a variable ($array) and then use unset($array[x]) (where x stands for desired array number, 1,2,3 etc) to remove particular array. Then use array_values() to re-index and load the array into another variable and then use a while loop and above solutions to dump the array (without any special characters) into target file.
$x=0;
while ($x <= $lines-1) //$lines is count($array) i.e. number of lines in array $array
{
$txt= "$array[$x]";
file_put_contents("file.txt", $txt, FILE_APPEND);
$x++;
}
Solution 10 - Php
just use file_put_contents('file',$myarray);
file_put_contents() works with arrays too.
Solution 11 - Php
Below Should work nice and more readable using <pre>
<?php
ob_start();
echo '<pre>';
print_r($array);
$outputBuffer = ob_get_contents();
ob_end_flush();
file_put_contents('your file name', $outputBuffer);
?>
Solution 12 - Php
test.php
<?php
return [
'my_key_1'=>'1111111',
'my_key_2'=>'2222222',
];
index.php
// Read array from file
$my_arr = include './test.php';
$my_arr["my_key_1"] = "3333333";
echo write_arr_to_file($my_arr, "./test.php");
/**
* @param array $arr <p>array</p>
* @param string $path <p>path to file</p>
* example :: "./test.php"
* @return bool <b>FALSE</b> occurred error
* more info: about "file_put_contents" https://www.php.net/manual/ru/function.file-put-contents.php
**/
function write_arr_to_file($arr, $path){
$data = "\n";
foreach ($arr as $key => $value) {
$data = $data." '".$key."'=>'".$value."',\n";
}
return file_put_contents($path, "<?php \nreturn [".$data."];");
}
Solution 13 - Php
echo "<pre>: ";
print_r($this->array_to_return_string($array));
protected function array_to_return_string($param) {
$str="[";
if($param){
foreach ($param as $key => $value) {
if(is_array($value) && $value){
$strx=$this->array_to_return_string($value);
$str.="'$key'=>$strx";
}else{
$str.="'$key'=>'$value',";
}
}
}
$str.="],";
return $str;
}
Solution 14 - Php
##first you can save the file to a file.##
file_put_contents($target_directory. $filename, '<?php ' . PHP_EOL . ' $' . $array_name. '= ' . var_export($array, true) . ';');
then you can read this file by include it or with file_get_content. If you want to add a new data to the same file;
file_put_contents($file_name, ' ' . PHP_EOL . ' $' . $array_name. '= ' . var_export($array, true) . ';', FILE_APPEND);
In this way, you can add data to the previous file, protect your data in the file, and call it whenever you want.