Print_r () with line break by Array element

5

I've been looking at some question of this style but I have not seen anything that serves me, so I put my question to you.

I have an object called $detalle that has an array with other arrays inside (excuse me, but I do not remember the name of this type of array) and I write the data using print_r() and file_put_contents() in a file called detallesPedido.txt .

This is the code I use:

$contenido = print_r($detalle, true);

file_put_contents("detallesPedido.txt", $contenido);

My problem is that in the file detalles.txt shows me all the data in the same line and I can not get each element of the array to be shown in a line.

I tried to use fwrite() but the same thing kept happening to me.

EDIT : Following the comment of @ A.Cedano I would like it to be shown as follows:

Array ( 
[a] => manzana 
[b] => banana 
[c] => Array ( 
   [0] => x 
   [1] => y 
   [2] => z )

Actually the bleeding is a little indifferent, but it is something like a "list".

EDIT2 : I've tried a simpler array.

array( 'mensaje'=>"el correo se ha enviado", 
       'datos'=> "m");

And it keeps coming online, instead of how it would correspond to print_r .

Thanks in advance!

    
asked by Exe 17.04.2018 в 12:40
source

1 answer

1

First of all tell you that your text file actually has the format you want only when you open it with the Windows text editor he does not see it that way. You can try to open it with Word or another editor and verify what I say. The problem is that some editors interpret line breaks more flexible than others. So Notepad expects each line break to end with the characters CR, LF (0x0d, 0x0a) and if it only finds one of them it does not represent it as you wish. The solution is to replace in the text that you want to store in the file all the line breaks by the constant PHP_EOL that depending on the Operating System in which you assign the indicated value so that your editor recognizes the jump line correctly. Here is the code:

$data = [
    'person' => [
        ['name' => 'dariel', 'age' => 27],
        ['name' => 'mily', 'age' => 24]
    ],
    'animal' => [
        ['name' => 'Floppy']
    ]
];

$contenido = print_r($data, true);
//Aqui es donde hago el reemplazo que comenté arriba
file_put_contents("arreglo.txt", preg_replace("/\n/", PHP_EOL, $contenido));

I hope it has helped you! Greetings

    
answered by 17.04.2018 / 14:49
source