473,387 Members | 1,575 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Writing an array to a text file

30
I have a function in my program to write an array to a text file, but every way I've tried results in the same result: when I open the file to check what's been written to it, all it displays is the word "Array" at the top. It's the last step I need to finish this assignment! I've tried a foreach loop, a listeach loop, and the simplest solution, shown below:

[PHP]function saveData($myFile)
{


if($file = fopen("employees.dat", "w")):
$numElements = count($myFile);
for($i = 0; $i < $numElements; $i++)
{
fwrite($file, $myFile[$i]);
}
fclose($file);

else:
echo("Error in opening file. Please re-submit");
echo("<A HREF ='gradedLab3.htm'>Return to form</A>");

endif;
}[/PHP]

None of these has helped. Any advice?
Feb 28 '07 #1
10 49367
cassbiz
202 100+
If all you are writing is "Array" I would look at that part of the script to see if that is all you are asking it to write there.

I know that you have done a lot of work but the output being the word "Array" makes me think that you want to look at that part.

Can you show your entire script? It may help us better to help you.

Good Luck.
Feb 28 '07 #2
tnspc
30
Thanks for the feedback. However, I'd already tested the code before posting this, and without going into too much detail, it is definitely passing the array properly into the function. (I used the print_r() method to display it, so I know for sure). The problem seems to be that the fwrite method doesn't work for arrays, only strings, even though each element of the array IS a string. Are there any special methods for writing an array? I've already tested everything else and it all works except the last function. (By the way, ignore most of the comments; they were part of the code to start with).

And, here's the complete code:

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. /* 
  3.    loadData: returns an array of lines in a file
  4.    Parameters: the name of the file to be loaded, a string
  5.            the default is "employees.dat"
  6.    Returns: the array of lines in that file
  7. */
  8.  
  9. //write loadData here
  10.    function loadData($defaultFileName = "employees.dat")
  11.   {
  12.      if(!$defaultFileName = file("employees.dat"))
  13.        {
  14.         echo('Error while opening file');
  15.        }
  16.  
  17.         return $defaultFileName;
  18.   }   
  19.  
  20.  
  21.  
  22. /*
  23.    searchData: searches an array for a string
  24.    Parameters: $myFile - the array to look through
  25.                $oldName - the string to look for
  26.    Returns: the index where the string is found in the array or -1 if not found
  27. */
  28.  
  29. //write searchData here
  30. function searchData($myFile, $oldName)
  31.      {
  32.     $a = $myFile;
  33.     $s = $oldName;
  34.  
  35.     $numElements = count($myFile);
  36.       for($i = 0; $i < $numElements; $i++)  
  37.         {
  38.          if((eregi($s, $a[$i])))
  39.         {
  40.         return $i;
  41.                 }
  42.          else
  43.         {
  44.          if($i == $numElements-1)        
  45.                   {
  46.               return -1;
  47.                     } 
  48.             else
  49.                {
  50.               $i++;
  51.                   }  
  52.                 }
  53.         }
  54.  
  55.       }
  56.  
  57.  
  58. /*
  59.    updateData: updates lines in an array
  60.    Parameters: $a - the array
  61.            $i - index in the array to update
  62.            $sOld - name in string to replace
  63.            $sNew - name to replace $sOld with
  64. */
  65.  
  66. //write updateData here
  67.     function updateData($myFile, $index, $oldName, $newName)
  68.         {
  69.          $a = $myFile;
  70.          $i = $index;
  71.          $sOld = $oldName;
  72.          $sNew = $newName;
  73.  
  74.          $a[$i] = eregi_replace($sOld,$sNew, $a[$i]);          
  75.              return array($a);
  76.  
  77.         }
  78.  
  79.  
  80.  
  81. /*
  82.    saveData: saves array to a file, does not save empty array elements
  83.    Parameters: $a - array to be saved
  84.            $defaultFilename - name of file, default value "employees.dat"
  85. */
  86. //write saveData here
  87.     function saveData($myFile)
  88.         {
  89. echo("<br>");
  90. print_r($myFile);        
  91. echo("<br>");
  92.  
  93.         if($file = fopen("employees.dat", "w")):
  94.            $numElements = count($myFile);
  95.            for($i = 0; $i < $numElements; $i++)
  96.            {            
  97.                     fwrite($file, $myFile[$i]);
  98.            }    
  99.             fclose($file);    
  100.  
  101.         else:
  102.            echo("Error in opening file. Please re-submit");
  103.            echo("<A HREF ='gradedLab3.htm'>Return to form</A>");        
  104.  
  105.         endif;
  106.         }
  107.  
  108.  
  109.  
  110.  
  111.  
  112.  
  113.    if(!empty($newName)):
  114.     $myFile = loadData();
  115.         $index = searchData($myFile,$oldName);
  116.     if($index == -1):
  117.         echo("<HTML><HEAD><TITLE>$name not found</TITLE></HEAD><BODY>");
  118.         echo("<B>$name</B> not found <BR>");
  119.         echo("<A HREF ='gradedLab3.htm'>Return to form</A>");
  120.             echo("<B>$name</B></HTML>");
  121.         exit();
  122.     else: 
  123.          //update name and save data
  124.          //call updateData here
  125.  
  126.            $myFile = updateData($myFile, $index, $oldName, $newName);
  127.            saveData($myFile);
  128.  
  129. ?>
  130.  
  131. <HTML>
  132. <HEAD>
  133. <TITLE>Employee Updated</TITLE>
  134. </HEAD>
  135. <BODY>
  136. <B><?php echo($oldName); ?></B> was updated <?php echo("to $newName"); ?><BR>
  137. <A HREF = "gradedLab3.htm">Return to Form</A>
  138.  
  139. </BODY>
  140. </HTML>
  141. <?php
  142.     endif;
  143.     else:
  144.  
  145. ?>
  146.  
  147. <HTML>
  148. <HEAD>
  149. <TITLE>No Name</TITLE>
  150. </HEAD>
  151. <BODY>
  152. <B>No name was submitted</B><BR>
  153. <A HREF = "gradedLab3.htm">Return to Form</A>
  154.  
  155. </BODY>
  156. </HTML>
  157.  
  158. <?php
  159.  
  160.     endif;
  161. ?>
Feb 28 '07 #3
Motoma
3,237 Expert 2GB
The function you are looking for is var_export().
Feb 28 '07 #4
tnspc
30
I checked that one... my issue is that I need this to write to a file instead of displaying on the screen. How would I go about doing that using this method?
Feb 28 '07 #5
Motoma
3,237 Expert 2GB
I checked that one... my issue is that I need this to write to a file instead of displaying on the screen. How would I go about doing that using this method?
Assign a variable to var_export() and then write the variable to a file.
Feb 28 '07 #6
tnspc
30
Code:


$file = fopen("employees.dat", "w");
fwrite($file, var_export($myFile));
fclose($file);

resulted in a blank "employees.dat" file and displayed the original array as associated with : array[0]=>.
Feb 28 '07 #7
Motoma
3,237 Expert 2GB
Code:


$file = fopen("employees.dat", "w");
fwrite($file, var_export($myFile));
fclose($file);

resulted in a blank "employees.dat" file and displayed the original array as associated with : array[0]=>.
It appears, then, that $myFile is an array with one element which is empty.
Feb 28 '07 #8
I was also trying to use var_export for arrays. What about this:
[PHP]

$FileName = "Some_File.txt";
$Data = file($FileName);
$Lines = count($Data);
...
for ($i=0; $i<$Lines; $i++){
$Array .= "$Data[$i]\n" ; // !!
}

[/PHP]
now you can write the $Array using fwrite() without problems.
Nov 5 '07 #9
@tnspc
Set the second arg to var_export to 1. This tells var_export to return its results as a string instead of writing to the terminal.

Expand|Select|Wrap|Line Numbers
  1. $file = fopen("employees.dat", "w");
  2. fwrite($file, var_export($myFile,1));
  3. fclose($file);
This worked for me
Feb 10 '09 #10
@Motoma
Kudos buddy. Worked well
May 3 '12 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: sp | last post by:
Hello everybody, I have an xml doc and I am trying to write the values from xml file to a tab delimited text file. Currently, what I am doing is I am reading xml file through XpathNavigaotr and...
4
by: jigi via DotNetMonster.com | last post by:
i have a compiled dll, and i want to see what values ar in certain methods during run time. i have built the release build . is there a way to write to a text file on my desktop or qa desktop? ...
5
by: cwbp15 | last post by:
Using Visual Studio C# When I ran the following code: System.IO; private void Button1_Click(object sender, System.EventArgs e) { //FileStream fs = File.Create(Server.MapPath("test.txt"));...
4
by: poldoj | last post by:
Hi all, I am trying to write the content of a variable to a text file. I am currently switching from VB 6 code to VB.NET. Here is the code in my vb 6 applications (this code works)...
3
by: poldoj | last post by:
First I would thank you all for the replies at my previous post. Say sorry for my poor english also. I have found where my problem came from. I am writing a string to a text box and write the...
0
by: Yunus's Group | last post by:
Yunus's Group May 23, 3:36 pm show options Newsgroups: microsoft.public.dotnet.languages.vb From: "Yunus's Group" <yunusasm...@gmail.com> - Find messages by this author Date: 23 May 2005...
2
by: Art | last post by:
Hi, I have a fairly large text file with data that I need to put into an Access Database. The text file is not uniform and I have to read it line by line in order to derive some of the fields. ...
4
by: Marc | last post by:
Hi, I have a button on a form that, when pressed, adds additional user defined buttons to the form. I need to be able to save the user preferences and thought the best way would be to write the...
42
by: psbasha | last post by:
Hi, Is it necessary in Python to close the File after reading or writing the data to file?.While refering to Python material ,I saw some where mentioning that no need to close the file.Correct me...
4
by: Gilles Ganault | last post by:
Hello I'm stumped as to why PHP fails writing into a text file, with the script being called through Apache: ============== # pwd /usr/local/www/data/ ============== # ll
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.