Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print array to a file

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));

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);

You could try:

$h = fopen('filename.txt', 'r+');
fwrite($h, var_export($your_array, true));

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


Quick and simple do this:

file_put_contents($filename, var_export($myArray, true));

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);

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;
  }