-1

I am trying to write an array to a file in php. If I do

$var = "Var";
fwrite($file, "<?php \$var = '$var';");

and I echo $var in the new file it will return "Var". But if I do the same thing with an array it will return "Array". How can I fix this?

3 Answers3

4

The var_export() function does exactly what you want: it outputs a variable in a way it can be used in a .php file. Please note that when using var_export, you should drop the quotes around your variable in the output string.

fwrite($file, "<?php \$var = ".var_export($var, true).";");
vixducis
  • 1,010
  • 1
  • 8
  • 22
0

You need to turn the array into a string that is separated by a comma. This is one of those problems where you will run into lots of edge cases. For instance, the below code will fail if one of the elements in the array contains a ' single quote character.

<?php

$hello = 'Hello';
$world = 'World';
$integer = 100;

$array = [
    $hello,
    $world,
    $integer
];

function add_quotes($e) {
    if (is_string($e))
        return sprintf("'%s'", $e);
    else
        return $e;
}

$php_string = '<?php
$array = [';
$php_string .= implode(',', array_map('add_quotes', $array));
$php_string .= '];';

$fp = fopen('output.php', 'w');
fwrite($fp, $php_string);

This will output

<?php
    $array = ['Hello','World',100];
Jacob Mulquin
  • 3,458
  • 1
  • 19
  • 22
  • This is dangerous. Any text string that already contains a quote will break it. – Tangentially Perpendicular Sep 29 '21 at 22:23
  • Yes I know, i stated as such in the answer. – Jacob Mulquin Sep 29 '21 at 22:23
  • @mulquin - Even if you pointed that out, wouldn't that make it an unsatisfactory answer since you don't know the data the OP wants to store? Especially since there are safer ways of doing it? – M. Eriksson Sep 29 '21 at 22:34
  • Not at all, the questioner does not even know that echoing an array results in `Array` so I'm going to guess they are a very new programmer. – Jacob Mulquin Sep 29 '21 at 22:36
  • That's kind of the point. If they are new to programming and we don't know the contents of the data, why then recommend a solution that only works in _some_ cases? Wouldn't that add more confusion and follow up questions in case their data _does_ contain single quotes? Specially since the above code basically manually does what `var_export()` does for you safer, without that restriction? – M. Eriksson Sep 29 '21 at 22:39
0

How you fix things depends very much on what you want to do with the stored data.

The simple example is to write each element separately:

<?php
$arr = ['Apple','Orange','Lemon'];
$fh = fopen('myFile.csv', 'w');
foreach($arr as $el) {
  fwrite ($fh, "$el\n");  // add a new line after each element to delimit them
}
fclose($fh);

You could create a CSV file with fputcsv():

<?php
$arr = ['Apple','Orange','Lemon'];
$fh = fopen('myFile.csv', 'w');
fputcsv($fh, $arr);
fclose($fh);

You could write JSON data:

<?php
$arr = ['Apple','Orange','Lemon'];
file_put_contents('myFile.json', json_encode($arr));

If you're feeling bold you could create an XML file (no snippet for this one, but trust me, it can be done).

You could write serialized PHP data (see serialize()) - not recommended.

Or you could create your own format for your specific application.

  • _"You could write serialized PHP data (see serialize()) - not recommended."_ - Why the "not recommended"? I would argue that it depends on the use case. – M. Eriksson Sep 29 '21 at 22:38
  • @MagnusEriksson I agree on the use case, but PHP serialised data is really only useful if you're going to unserialize it with PHP. There are other formats (I've mentioned three) that are more portable. – Tangentially Perpendicular Sep 29 '21 at 22:43
  • 1
    Absolutely. I just think it's a good idea to give a background to when it isn't recommended instead of having it as a blanket statement. There are already too many misconceptions about things. I would also argue that the last statement "create your own format" should be the one that's not recommended for the vast majority of cases. Doing that usually ends up with you spending a lot of time fixing bugs for different edge cases you haven't thought of. – M. Eriksson Sep 29 '21 at 22:53