1

I know I can print an array using print_r() function in PHP like this

print_r($array);

And to make it look pretty in the browser, I can wrap it up with the HTML <pre> block like this

echo '<pre>';
print_r($array);
echo '</pre>';

But, how can I write the second nice output to a file not to a browser using HTML?

Here is what I have tried

$file = fopen('test.log', 'a+');
fwrite($file, print_r($this->header, TRUE) . PHP_EOL);
fclose($file);

But, that does not write the array's content nicely in the test.log file. it writes it as a data dump which is hard to read.

How can I nicely print the array content for easy read

2
  • 1
    have you tried using a foreach? Commented Aug 27, 2015 at 16:42
  • 1
    Replace each space between newline and first alphanumerical character with \t (tabulator). This should create nice indents. Commented Aug 27, 2015 at 16:46

3 Answers 3

2

I found 2 way to do this. the first one, the credit goes to Md. Khairul Islam

this method will use a foreach to write the array content to the file

private function fwriteArray($result, $file){

    if( !is_array($result) && !is_object($result)) {    
            return false;
    }

    foreach($result as $k => $v){
        if(is_array($v) || is_object($v) ){

            $this->fwriteArray($v, $file);

        } else {
            fwrite($file, '    [' . $k.'] => ' .  $v . PHP_EOL);
        }
    }
}

second method is to convert the array to json string and use JSON_PRETTY_PRINT to print the data nicely

fwrite($file, PHP_EOL . str_replace("\n", PHP_EOL, json_encode( $myArray, JSON_PRETTY_PRINT)));
Sign up to request clarification or add additional context in comments.

Comments

0

Try the following code. I do not know what $this->header is working inside your webapp. But assuming its a array . the following example works file for single array .

 $text="";
 $file = fopen('test.log', 'a+');
 foreach($this->header as $key=>$val)
  {
  $text.="$key=>$val \n\r";
  }
fwrite($file, $text);
fclose($file);

1 Comment

I won't format it nicely, which is key problem for author.
0

You can use output control.

ob_start();
print_r($array);
$content = ob_get_clean();

$file = fopen('test.log', 'a+');
fwrite($file, $content . PHP_EOL);
fclose($file);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.