views:

108

answers:

3

trying to write an array to a text file, but it is failed, can anybody say, WHY?

    $filename= 't12a';


  for ($pnum = 1; $pnum <= 15; $pnum++){
                $bbal = 3;
                $ipmnt = 14 * 5;
                $ppmnt = 26 - 7;
                $ebal = 48 - 4;
                $ccint = 54 + 45;
                $cpmnt = 25 + 54;


                $db_data_txt[] = array('pn' => $pnum, 'bb' => sprintf("%01.2f",$bbal),'ip'=>sprintf("%01.2f",$ipmnt),'pp'=>sprintf("%01.2f",$ppmnt),'eb'=>sprintf("%01.2f",$ebal),'ci'=>sprintf("%01.2f",$ccint),'cp'=>sprintf("%01.2f",$cpmnt));



  }


 $con= $db_data_txt;


if ( ! write_file("./files/{$filename}.doc", $con))
{
     echo 'Unable to write the file';
}
else
{
     echo 'File written!';
}
+1  A: 

I think that you can only write characters to a file in PHP.

If you want to write an array (or any other complex data structure) to a file, you may need to serialize it. See: http://php.net/manual/en/function.serialize.php.

PS: I cannot find any definition for write_file, is it the same as http://php.net/manual/en/function.file-put-contents.php?

Chris
+2  A: 

If $con is an array, either do

write_file( "./files/{$filename}.doc", var_export($con, true) );

to write a parseable representation of the array to file or

write_file( "./files/{$filename}.doc", print_r($con, true) );

to write the output of print_r to the file.

The true in both functions means they will return their output instead of outputting it.

Gordon
A: 

First of all make sure that you are loading the helper file:

$this->load->helper('file');

After that, try this:

if (! write_file('./path/to/file.php', var_export($con, true)))
{
     echo 'Unable to write the file';
}
else
{
     echo 'File written!';
}

Also make sure that:

  • File/Folder is writable, chmod to 755
  • You are specifying the correct path
  • Try adding $_SERVER['DOCUMENT_ROOT'] to your path
Sarfraz