Writing an array to a text file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tnspc
    New Member
    • Feb 2007
    • 30

    Writing an array to a text file

    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($myFil e)
    {


    if($file = fopen("employee s.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.ht m'>Return to form</A>");

    endif;
    }[/PHP]

    None of these has helped. Any advice?
  • cassbiz
    New Member
    • Oct 2006
    • 202

    #2
    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.

    Comment

    • tnspc
      New Member
      • Feb 2007
      • 30

      #3
      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:

      Code:
      <?php
      /* 
         loadData: returns an array of lines in a file
         Parameters: the name of the file to be loaded, a string
      	       the default is "employees.dat"
         Returns: the array of lines in that file
      */
      
      //write loadData here
         function loadData($defaultFileName = "employees.dat")
        {
           if(!$defaultFileName = file("employees.dat"))
             {
              echo('Error while opening file');
             }
      
              return $defaultFileName;
        }   
      
      
      
      /*
         searchData: searches an array for a string
         Parameters: $myFile - the array to look through
                     $oldName - the string to look for
         Returns: the index where the string is found in the array or -1 if not found
      */
      
      //write searchData here
      function searchData($myFile, $oldName)
           {
      	$a = $myFile;
      	$s = $oldName;
             
      	$numElements = count($myFile);
      	  for($i = 0; $i < $numElements; $i++)  
      	    {
      	     if((eregi($s, $a[$i])))
      		{
      		return $i;
                      }
      	     else
      		{
      		 if($i == $numElements-1)		
      	              {
      		      return -1;
                	      } 
         		 else
       		      {
      		      $i++;
      	              }  
                      }
      	    }
            
            }
      
      
      /*
         updateData: updates lines in an array
         Parameters: $a - the array
      	       $i - index in the array to update
      	       $sOld - name in string to replace
      	       $sNew - name to replace $sOld with
      */
      
      //write updateData here
      	function updateData($myFile, $index, $oldName, $newName)
      	    {
      	     $a = $myFile;
      	     $i = $index;
      	     $sOld = $oldName;
      	     $sNew = $newName;
                   
      	     $a[$i] = eregi_replace($sOld,$sNew, $a[$i]); 	     
                   return array($a);
                   
      	    }
      
      
      
      /*
         saveData: saves array to a file, does not save empty array elements
         Parameters: $a - array to be saved
      	       $defaultFilename - name of file, default value "employees.dat"
      */
      //write saveData here
      	function saveData($myFile)
      	    {
      echo("<br>");
      print_r($myFile);		
      echo("<br>");
      		
      		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;
      	    }
      
      
      
      
      
      
         if(!empty($newName)):
      	$myFile = loadData();
              $index = searchData($myFile,$oldName);
      	if($index == -1):
      	    echo("<HTML><HEAD><TITLE>$name not found</TITLE></HEAD><BODY>");
      	    echo("<B>$name</B> not found <BR>");
      	    echo("<A HREF ='gradedLab3.htm'>Return to form</A>");
                  echo("<B>$name</B></HTML>");
      	    exit();
      	else: 
      	     //update name and save data
      	     //call updateData here
      	     
      	       $myFile = updateData($myFile, $index, $oldName, $newName);
      	       saveData($myFile);
      
      ?>
      
      <HTML>
      <HEAD>
      <TITLE>Employee Updated</TITLE>
      </HEAD>
      <BODY>
      <B><?php echo($oldName); ?></B> was updated <?php echo("to $newName"); ?><BR>
      <A HREF = "gradedLab3.htm">Return to Form</A>
      
      </BODY>
      </HTML>
      <?php
      	endif;
      	else:
      
      ?>
      
      <HTML>
      <HEAD>
      <TITLE>No Name</TITLE>
      </HEAD>
      <BODY>
      <B>No name was submitted</B><BR>
      <A HREF = "gradedLab3.htm">Return to Form</A>
      
      </BODY>
      </HTML>
      
      <?php
      
      	endif;
      ?>
      Last edited by Niheel; May 3 '12, 01:23 PM. Reason: codetags

      Comment

      • Motoma
        Recognized Expert Specialist
        • Jan 2007
        • 3236

        #4
        The function you are looking for is var_export().

        Comment

        • tnspc
          New Member
          • Feb 2007
          • 30

          #5
          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?

          Comment

          • Motoma
            Recognized Expert Specialist
            • Jan 2007
            • 3236

            #6
            Originally posted by tnspc
            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.

            Comment

            • tnspc
              New Member
              • Feb 2007
              • 30

              #7
              Code:


              $file = fopen("employee s.dat", "w");
              fwrite($file, var_export($myF ile));
              fclose($file);

              resulted in a blank "employees. dat" file and displayed the original array as associated with : array[0]=>.

              Comment

              • Motoma
                Recognized Expert Specialist
                • Jan 2007
                • 3236

                #8
                Originally posted by tnspc
                Code:


                $file = fopen("employee s.dat", "w");
                fwrite($file, var_export($myF ile));
                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.

                Comment

                • AdrianoMT
                  New Member
                  • Nov 2007
                  • 5

                  #9
                  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.

                  Comment

                  • shrewmouse
                    New Member
                    • Feb 2009
                    • 1

                    #10
                    var_export takes two options

                    Originally posted by tnspc
                    Code:


                    $file = fopen("employee s.dat", "w");
                    fwrite($file, var_export($myF ile));
                    fclose($file);

                    resulted in a blank "employees. dat" file and displayed the original array as associated with : array[0]=>.
                    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.

                    Code:
                    $file = fopen("employees.dat", "w");
                    fwrite($file, var_export($myFile,1));
                    fclose($file);
                    This worked for me

                    Comment

                    • zameer55
                      New Member
                      • May 2012
                      • 1

                      #11
                      @Motoma
                      Kudos buddy. Worked well

                      Comment

                      Working...