[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

change column header name when fetching .csv file via ftp

Posted on 2009-12-19
26
Medium Priority
?
389 Views
Last Modified: 2013-12-12
i'm fetching a csv file via ftp using the code below.

does anyone know if it would be possible to change the columns heading in the csv file at the same time as saving this csv file to my server?

so something like

column 1 = my columns name1
column 2 = my columns name2
column 3 = my columns name2

if this is possible could someone please give exampls of how in code please. thanks
zac

<?php 
                // define some variables 
        $folder_path = "C:/Inetpub/Www_root/shop/temp/";  
        $local_file = "file.csv"; 
        $server_file = "file.csv"; 
         
        //-- Connection Settings 
        $ftp_server = "ftp.server.co.uk"; // Address of FTP server. 
        $ftp_user_name = "user"; // Username 
        $ftp_user_pass = "name"; // Password 
        #$destination_file = "FILEPATH";  
         
        // set up basic connection 
        $conn_id = ftp_connect($ftp_server); 
         
        // login with username and password 
        $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 
         
        // try to download $server_file and save to $local_file 
        if (ftp_get($conn_id, $folder_path . $local_file, $server_file, FTP_BINARY)) { 
            echo "Successfully written to $local_file\n"; 
        } else { 
            echo "There was a problem\n"; 
        } 
         
        // close the connection 
        ftp_close($conn_id); 
?>

Open in new window

0
Comment
Question by:bede123
  • 13
  • 13
26 Comments
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26087595
FTP functions are all documented here:
http://us2.php.net/manual/en/ref.ftp.php

I think the answer is "No, not with FTP" - it really is all about transferring files, not modifying them.  You would want to consider a different way of getting the file - maybe with file() - then you can modify array position zero:
http://us2.php.net/manual/en/function.file.php

Or you can use FTP to get the file and process it after it is retrieved.

best, ~Ray
0
 
LVL 1

Author Comment

by:bede123
ID: 26087621
yes i think processing after i have fetched it will be the way to go. any ideas on where to start with this? please bear in mind this is my first ever php project. thanks
zac
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26087647
It's a good place to start.

Forget the FTP part of it for now - just make yourself a test file on a local machine.  Three lines will do, something like this:

First, Last, Foo
Ray, Paseur, Father
John, Paseur, Son

Then read that little file with file() and you will get an array.

Print the array with something like this:
var_dump($array);

Post that output back here and we can work through the changes you want to make.
0
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 
LVL 1

Author Comment

by:bede123
ID: 26087683
AHA ok will do.

it may take me a while to do just that basic stuff so please dont think i have abandoned the post. Thanks
0
 
LVL 1

Author Comment

by:bede123
ID: 26087712
ok think i have done that ok.

here is what is outputted when that page is run:

Line #0 : first, last, foo
Line #1 : ray, paseur, father
Line #2 : john, paseur, son
NULL
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26087721
Looks almost right.  If you do this it makes var_dump() output easier to read.  You can also use "view source"

echo "<pre>";
var_dump($array);
echo "</pre>";

So please run it again and post the EXACT OUTPUT of var_dump here.  Thanks, ~Ray
0
 
LVL 1

Author Comment

by:bede123
ID: 26087729
you mean like this?

Line #<b>0</b> : first, last, foo
<br />
Line #<b>1</b> : ray, paseur, father
<br />
Line #<b>2</b> : john, paseur, son<br />
<pre>NULL
</pre>
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26087766
No, something is still not right.  I will make up an example for you.  Back in a moment.
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 26087778
Here is what I get from running the code in the snippet

<pre>
array(3) {
  [0]=>
  string(17) "First, Last, Foo
"
  [1]=>
  string(20) "Ray, Paseur, Father
"
  [2]=>
  string(17) "John, Paseur, Son"
}

<?php // RAY_temp_bede123.php
 
// REPORT ALL THE ERRORS WHILE WE ARE IN DEVELOPMENT MODE
error_reporting(E_ALL);
 
// READABILITY FOR VAR DUMPS
echo "<pre>\n";
 
// THE FILE CONTAINS SOMETHING LIKE THIS:
// First, Last, Foo
// Ray, Paseur, Father
// John, Paseur, Son
 
// READ THE FILE INTO AN ARRAY
$arr = file('RAY_temp_bede123.txt');
 
// VISUALIZE THE ARRAY
var_dump($arr);

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26087811
Notice that we have an array - each line of the array is one line of the file.  Each line is terminated by the PHP end-of-line character (look up PHP_EOL for more information) and that terminator is what causes the final quote marks to be on separate lines in the display above.

Now we are going to change the first line to replace "Foo"  We will use the "explode" function to do part of this.  We will also use foreach() and implode()
<?php // RAY_temp_bede123.php
 
// REPORT ALL THE ERRORS WHILE WE ARE IN DEVELOPMENT MODE
error_reporting(E_ALL);
 
// READABILITY FOR VAR DUMPS
echo "<pre>\n";
 
// THE FILE CONTAINS SOMETHING LIKE THIS:
// First, Last, Foo
// Ray, Paseur, Father
// John, Paseur, Son
 
// READ THE FILE INTO AN ARRAY
$arr = file('RAY_temp_bede123.txt');
 
// VISUALIZE THE ARRAY
var_dump($arr);
  
// GRAB THE FIRST LINE OF THE FILE
$first_line = $arr[0];
 
// BREAK IT INTO AN ARRAY - SEPARATING ON THE COMMAS
$first_line_parts = explode(',', $first_line);
 
// ITERATE OVER THE PARTS
foreach ($first_line_parts as $pointer => $one_part)
{
    // IF THIS IS FOO...
    if (trim($one_part) == 'Foo')
    {
        // CHANGE IT TO RELATIONSHIP
        $first_line_parts[$pointer] = ' Relationship';
    }
}
 
// REASSEMBLE THE PARTS INTO THE FIRST LINE OF THE ARRAY
$arr[0] = implode(',', $first_line_parts) . PHP_EOL;
 
// SHOW THE NEW ARRAY
var_dump($arr);

Open in new window

0
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 2000 total points
ID: 26087856
The last step would be to write the new file.  With PHP you can do that in one line of code!

Something like this:
file_put_contents(RAY_temp_NEW_bede123.txt', implode($arr));

Hope that helps, ~Ray
0
 
LVL 1

Author Comment

by:bede123
ID: 26087859
ok... so at first it woudlnt work but then i realised it was case sensitive.

so now it is working and has chnaged 'foo' to 'Relationship'

so basically all i need to do i repeat this:

{ if (trim($one_part) == 'foo')
{$first_line_parts[$pointer] = ' Relationship';}

{ if (trim($one_part) == '2ndCol')
{$first_line_parts[$pointer] = ' NewNameCol2';}

{ if (trim($one_part) == '3rdCol')
{$first_line_parts[$pointer] = ' NewNameCol3';}

is that correct?



0
 
LVL 1

Author Comment

by:bede123
ID: 26087868
ok hang on so let me put a dummy file together and show you.....
0
 
LVL 1

Author Comment

by:bede123
ID: 26087891
ok, thought i was on the right tracks but the code below doesnt actually work :-(
<?php // RAY_temp_bede123.php 
  
// REPORT ALL THE ERRORS WHILE WE ARE IN DEVELOPMENT MODE 
error_reporting(E_ALL); 
  
// READABILITY FOR VAR DUMPS 
echo "<pre>\n"; 
  
// THE FILE CONTAINS SOMETHING LIKE THIS: 
// First, Last, Foo 
// Ray, Paseur, Father 
// John, Paseur, Son 
  
// READ THE FILE INTO AN ARRAY 
$arr = file('../temp/test.txt'); 
  
// VISUALIZE THE ARRAY 
var_dump($arr); 
   
// GRAB THE FIRST LINE OF THE FILE 
$first_line = $arr[0]; 
  
// BREAK IT INTO AN ARRAY - SEPARATING ON THE COMMAS 
$first_line_parts = explode(',', $first_line); 
  
// ITERATE OVER THE PARTS 
foreach ($first_line_parts as $pointer => $one_part) 

{ if (trim($one_part) == 'foo') 
{ $first_line_parts[$pointer] = 'Relationship'; }

{ if (trim($one_part) == 'first')
{ $first_line_parts[$pointer] = 'FirstName';}

{ if (trim($one_part) == 'last')
{ $first_line_parts[$pointer] = 'LastName';}
	
	 
}
  
// REASSEMBLE THE PARTS INTO THE FIRST LINE OF THE ARRAY 
$arr[0] = implode(',', $first_line_parts) . PHP_EOL; 
  
// SHOW THE NEW ARRAY 
var_dump($arr); 

// SAVE THE NEW FILE
file_put_contents(completed_file.txt', implode($arr));

?>

Open in new window

0
 
LVL 1

Author Comment

by:bede123
ID: 26087915
ok, think i got it!

please can you check to make sure.

thanks
zac

<?php // RAY_temp_bede123.php 
  
// REPORT ALL THE ERRORS WHILE WE ARE IN DEVELOPMENT MODE 
error_reporting(E_ALL); 
  
// READABILITY FOR VAR DUMPS 
echo "<pre>\n"; 
  
// THE FILE CONTAINS SOMETHING LIKE THIS: 
// First, Last, Foo 
// Ray, Paseur, Father 
// John, Paseur, Son 
  
// READ THE FILE INTO AN ARRAY 
$arr = file('../temp/test.txt'); 
  
// VISUALIZE THE ARRAY 
var_dump($arr); 
   
// GRAB THE FIRST LINE OF THE FILE 
$first_line = $arr[0]; 
  
// BREAK IT INTO AN ARRAY - SEPARATING ON THE COMMAS 
$first_line_parts = explode(',', $first_line); 
  
// ITERATE OVER THE PARTS 
foreach ($first_line_parts as $pointer => $one_part) 

{ if (trim($one_part) == 'foo') 
 $first_line_parts[$pointer] = 'Relationship'; 
}
foreach ($first_line_parts as $pointer => $one_part) 
{ if (trim($one_part) == 'first')
 $first_line_parts[$pointer] = 'FirstName';
}
foreach ($first_line_parts as $pointer => $one_part) 
{ if (trim($one_part) == 'last')
 $first_line_parts[$pointer] = 'LastName';
	
	 
}
  
// REASSEMBLE THE PARTS INTO THE FIRST LINE OF THE ARRAY 
$arr[0] = implode(',', $first_line_parts) . PHP_EOL; 
  
// SHOW THE NEW ARRAY 
var_dump($arr); 

// SAVE THE NEW FILE
file_put_contents(completed_file.txt', implode($arr));

?>

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26087920
"doesnt actually work" is not a diagnostic message I recognize.  When you ran the script did it produce any output or messages that you would like to share with us?

Couple of other points... The names of variables (but not Classes or functions) are CASE SENSITIVE in PHP.  $foo is not the same as $Foo.  But var_dump() is the same as var_Dump().

The contents of strings are treated in a case-sensitive manner by all functions in PHP, except those functions that are explicitly known to be case-insensitive.  String comparisons are always case-sensitive.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26087931
Please have another look at lines 26 thru 41 in your recent code snippet.  There is a practice called "coding standards" that guides us when we use those curly-braces to indicate the control structures.  Check my example above to see how the indentation and the lineup works for those things, and let me know if you have any questions about that part.

Also, line 50 can be expected to throw a parse error due to unbalanced quote marks around the file name.
0
 
LVL 1

Author Comment

by:bede123
ID: 26087973
hmm, i cant see what i'm doing wrong with this bit now.

ive tried different combinations.... i took another look at your code and changed it but still no cigar!


// ITERATE OVER THE PARTS 
foreach ($first_line_parts as $pointer => $one_part) 
{ if (trim($one_part) == 'foo') 
{$first_line_parts[$pointer] = 'Rel';
}

{ if (trim($one_part) == 'first')
{$first_line_parts[$pointer] = 'FirstNa';
}

{ if (trim($one_part) == 'last')
{$first_line_parts[$pointer] = 'LastNa';
}

Open in new window

0
 
LVL 1

Author Comment

by:bede123
ID: 26088064
ok, sorry, got it. sometime you just cant see what's right in front of you.

i've tested this a couple of times and seems to be working fine


// ITERATE OVER THE PARTS 
foreach ($first_line_parts as $pointer => $one_part) 
{ if (trim($one_part) == 'foo') 
{$first_line_parts[$pointer] = 'Rel';
}
}
foreach ($first_line_parts as $pointer => $one_part) 
{ if (trim($one_part) == 'first')
{$first_line_parts[$pointer] = 'FirstNa';
}
}
foreach ($first_line_parts as $pointer => $one_part) 
{ if (trim($one_part) == 'last')
{$first_line_parts[$pointer] = 'LastNa';
}
}

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26088103
It is going to be easier to handle if you keep the proper indentations in the control structures!
0
 
LVL 1

Author Comment

by:bede123
ID: 26088122
oh ok, i didnt realise the indentations where important to be honest.

i'll go over it again and copy the indentations.

so if there anything else i need to do, do you think?

thanks
zac


0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26088160
The advantages of the indentations become apparent when you have to read a LOT of code and figure out the logic paths.  It's just a good habit to have.  If you want to post the finished code, I will be glad to take a look.  Have you been testing along the way as you developed it?
0
 
LVL 1

Author Comment

by:bede123
ID: 26088232
yes, have been testing and it 'seems' to be ok. its saving the file ok and its the correct place.

so now i just need to go through and match up all my column headers - there's about 70!!

so... i'm wondering now if there is some sort of 'transaction' tag that i can wrap my ftp code + the array code in and force the two scripts to run at the same time, or at least one after the other?


<?php // RAY_temp_bede123.php 
  
// REPORT ALL THE ERRORS WHILE WE ARE IN DEVELOPMENT MODE 
error_reporting(E_ALL); 
  
// READABILITY FOR VAR DUMPS 
echo "<pre>\n"; 
  
// THE FILE CONTAINS SOMETHING LIKE THIS: 
// First, Last, Foo 
// Ray, Paseur, Father 
// John, Paseur, Son 
  
// READ THE FILE INTO AN ARRAY 
$arr = file('../temp/test.txt'); 
  
// VISUALIZE THE ARRAY 
var_dump($arr); 
   
// GRAB THE FIRST LINE OF THE FILE 
$first_line = $arr[0]; 
  
// BREAK IT INTO AN ARRAY - SEPARATING ON THE COMMAS 
$first_line_parts = explode(',', $first_line); 
  
// ITERATE OVER THE PARTS 
foreach ($first_line_parts as $pointer => $one_part) 
{ 
	if (trim($one_part) == 'foo') 
	{
		$first_line_parts[$pointer] = 'Rel';
}
}
foreach ($first_line_parts as $pointer => $one_part) 
{ 
	if (trim($one_part) == 'first')
	{
		$first_line_parts[$pointer] = 'FirstNa';
}
}

foreach ($first_line_parts as $pointer => $one_part) 
{ 
	if (trim($one_part) == 'last')
	{
			$first_line_parts[$pointer] = 'LastNa';
}

}

  
// REASSEMBLE THE PARTS INTO THE FIRST LINE OF THE ARRAY 
$arr[0] = implode(',', $first_line_parts) . PHP_EOL; 
  
// SHOW THE NEW ARRAY 
var_dump($arr); 

// SAVE THE NEW FILE
file_put_contents('../temp/completed_file.csv', implode($arr));

?>

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26088388
I would just cobble the two scripts together into one script.  First run the FTP part of it, then run the replacement part.
0
 
LVL 1

Author Comment

by:bede123
ID: 26088394
thanks so much for your help with this. really appreciate it. thanks

zac

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26088825
You're welcome, and thanks for the points.  Best of luck with it! ~Ray
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Configuring network clients can be a chore, especially if there are a large number of them or a lot of itinerant users.  DHCP dynamically manages this process, much to the relief of users and administrators alike!
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Viewers will learn how to properly install and use Secure Shell (SSH) to work on projects or homework remotely. Download Secure Shell: Follow basic installation instructions: Open Secure Shell and use "Quick Connect" to enter credentials includi…
Suggested Courses
Course of the Month19 days, 14 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question