205

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.

Gordon
  • 312,688
  • 75
  • 539
  • 559
Atif
  • 10,623
  • 20
  • 63
  • 96

14 Answers14

352

Either var_export or set print_r to return the output instead of printing it.

Example from PHP manual

$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));
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • How can you ONLY save the contents of the array and not the entire array "[0] => blah"?? – user1899415 Aug 22 '13 at 05:38
  • 15
    @user1899415 `implode` the array with `PHP_EOL` and write the resulting string to file. – Gordon Aug 22 '13 at 08:56
  • 16
    `var_export` is better if you would like to save the file in php syntax. `print_r` returns `[m] => monkey` but `var_export` returns `'m' => 'monkey'` – Pedram Behroozi Oct 05 '13 at 09:28
  • Is there a way write the contents of the array, printed in a similar format, to the end of a file? – Wold Jul 14 '14 at 20:19
  • 1
    @Wold yes, check the $flags option in file_put_contents. – Gordon Jul 14 '14 at 20:46
  • 5
    @Wold use FILE_APPEND for this example: **file_put_contents('filename.txt', print_r($b, true), FILE_APPEND);** it will add them at the end of the file without overwriting each time. Furthermore, you may change it to: **print_r($b, true) . "\n"** to add extra line break or new line. – Tarik Feb 01 '17 at 11:33
  • It works but it removes quotes around the array key and value. Any solution for that? – Parth Vora Jul 04 '17 at 13:34
  • @ParthVora try `var_export` instead of `print_r` and make sure to look up both functions on http://php.net (or just click the links on top of the answer) – Gordon Jul 04 '17 at 13:37
57

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);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
30

You could try:

$h = fopen('filename.txt', 'r+');
fwrite($h, var_export($your_array, true));
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 1
    Add the second param of `true` to var_export, else there is no content to write to the file. – Progrock Jan 05 '16 at 01:54
  • var_export was a better solution in my experience as it wraps the array variable in quotes so handles better when using include/require to access the array values – Pete - iCalculator Sep 22 '17 at 14:41
27

file_put_contents($file, print_r($array, true), FILE_APPEND)

binaryLV
  • 9,002
  • 2
  • 40
  • 42
13

Quick and simple do this:

file_put_contents($filename, var_export($myArray, true));
alexwenzel
  • 2,361
  • 2
  • 15
  • 18
  • 1
    Correct answer, as THIS formats the code in real PHP syntax (the answers with print_r dont do that) – Sliq Jul 27 '22 at 12:58
8

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);
Ahmad
  • 4,224
  • 8
  • 29
  • 40
8

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);
Vivek Tailor
  • 206
  • 3
  • 6
5

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;
  }
Dieter Gribnitz
  • 5,062
  • 2
  • 41
  • 38
  • 1
    As far as i know print_r does not output the data in a format that can be copied and pasted as working php code.This will format output in a way that can be copied and pasted as a working array. – Dieter Gribnitz Jun 13 '13 at 11:47
2

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++;
    }
Sumit
  • 31
  • 2
2

just use file_put_contents('file',$myarray); file_put_contents() works with arrays too.

Patrick Mutwiri
  • 1,301
  • 1
  • 12
  • 23
  • 2
    This should really be the accepted answer in my opinion, although it's worth noting that file_put_contents can only work with a single array for it's second argument. – user3610279 Apr 25 '18 at 22:46
  • Prints "Array" as text for associative arrays. – yenren Jan 17 '21 at 09:24
1

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);
?>
kamal pal
  • 4,187
  • 5
  • 25
  • 40
1

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."];");
}
1
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;
}
wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29
-1

##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.