Home > database >  How Do I Write An Array To A File PHP?
How Do I Write An Array To A File PHP?

Time:09-30

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related