473,545 Members | 386 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Remove columns from CSV using a php script

7 New Member
Hello all. Not sure if this is the correct place to ask this but I am new to php and I am building a script to remove certain columns in a comma delimited file plus other things. My problem is removing the columns using a php script. Im not sure if I should use $temp or what. Could anyone please help me out. Thanks and glad to be a member.

JSchofield
Jan 18 '07 #1
11 10933
ronverdonk
4,258 Recognized Expert Specialist
Welcome to our community!

The following snippet from the PHP documentation (see fgetcsv) could help you. It reads a CSV file and echoes the data fields from each row. You can easily modify that to build a new file from the data. Holler if it doens't work out.[php]<?php
$row = 1;
$handle = fopen("test.csv ", "r");
while (($data = fgetcsv($handle , 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle) ;
?> [/php]
Ronald :cool:
Jan 18 '07 #2
jschofield
7 New Member
That did work. Thank you very much!! You have been a great help to me.
Johnnie

Welcome to our community!

The following snippet from the PHP documentation (see fgetcsv) could help you. It reads a CSV file and echoes the data fields from each row. You can easily modify that to build a new file from the data. Holler if it doens't work out.[php]<?php
$row = 1;
$handle = fopen("test.csv ", "r");
while (($data = fgetcsv($handle , 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle) ;
?> [/php]
Ronald :cool:
Jan 18 '07 #3
jschofield
7 New Member
I am now trying to add two columns (fields) together. Below is my code. Im using the . to add the two columns but it is not working for me. My output is still has the two seperate fields. I am actually trying to put an area code that is in one colmn and a phone number that is in another together to make a 10 digit number in one field. I am taking out some of the fields. Any idea why it isnt adding the two columns? Thanks again.
Johnnie

$oldphone = array($row[11].$row[12]);
$phone = implode( "", $oldphone);
$temp = array($row[0],$row[1],$row[2],$row[10],$phone,$row[13],$row[] = "English");


Welcome to our community!

The following snippet from the PHP documentation (see fgetcsv) could help you. It reads a CSV file and echoes the data fields from each row. You can easily modify that to build a new file from the data. Holler if it doens't work out.[php]<?php
$row = 1;
$handle = fopen("test.csv ", "r");
while (($data = fgetcsv($handle , 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle) ;
?> [/php]
Ronald :cool:
Jan 18 '07 #4
ronverdonk
4,258 Recognized Expert Specialist
You'd better show YOUR code, so I can see how you constructed these $row values.

Ronald :cool:
Jan 18 '07 #5
jschofield
7 New Member
Im sorry. Here is all of my code. Thanks. Johnnie
[php]
<?php

$inputfile = "C:/SMDIM/Data/StudentDemograp hics_AllActive. txt";
$outputfile = "C:/SMDIM/Data/Roanoke_City_St udent_Data.csv" ;
$logfilename = "C:/SMDIM/Logs/Roanoke_City_St udent_Log.txt";
include'C:/SMDIM/Translators/importlibrary.i nc.php';
$count = 0;
//open the file
if(!$outfilefp = fopen($outputfi le, "w")) {
wlogdie("Failed to open $outputfile");
}else{
wlog("Opened $outputfile for writing");
}

if(!$inputfp = fopen($inputfil e, "r")) {
wlogdie("Failed to open $inputfile");
}else{
wlog("Opened $inputfile for reading");
}

//add English language codes to the end of each line
//Keep needed lines and push unwanted out

while ($row = fgetcsv($inputf p, 1000, ",")){
$oldphone = array($row[11].$row[12]);
$phone = implode( "", $oldphone);
$temp = array($row[0],$row[1],$row[2],$row[10],$phone,$row[13],$row[] = "English");
writeline($outf ilefp, $temp);
$count++;
}
if($count !== '0') {
wlog("finished the import with a total of $count records");
}else{
wlog("Failed to import data");
}

?>[/php]
You'd better show YOUR code, so I can see how you constructed these $row values.

Ronald :cool:
Next time show the code enclosed in tags! Makes it a lot better to read from a screen! - Ronald
Jan 18 '07 #6
jschofield
7 New Member
Sorry here is the import.inc.php that my code refers too as well.

<?

function wlogDie ($str) {
global $logfp;

wlog($str);
fclose($logfp);
die(-1);
}
function wlog ($str) {
global $logfp;
echo $str . "\n";
fwrite($logfp, date("Y-m-d H:i:s") . " - $str\r\n");
}

function writeLine ($stufile, $row) {
$sisline = '"' . implode('","',$ row) . "\"\n";
if (!fwrite($stufi le,$sisline)) {
fclose($stufile );
wlogDie("failed to write student line to import file: $sisline");
}
}

function andList ($row) {
$line = NULL;
for ($x = 0; $x < count($row); $x++) {
if ($line === NULL) {
$line = $row[$x];
} else if ( $x == (count($row) -1) ) {
$line .= " and " . $row[$x];
} else {
$line .= ", " . $row[$x];
}
}
return $line;
}

$logfp = fopen($logfilen ame,"a");
if (!$logfp) {
exit(-1);
}
/*************** *************** ***********/


?>
Jan 18 '07 #7
ronverdonk
4,258 Recognized Expert Specialist
Why don't you just concatenate the 2 $row-fields in a string. Like this
Expand|Select|Wrap|Line Numbers
  1. $phone = $row[11].$row[12];
Ronald :cool:
Jan 18 '07 #8
jschofield
7 New Member
I did and it is not combining the two columns. I might add that the main file is a txt and in the php script I have it saving as a csv. I wouldnt think that would have anything to do with it. I really appreciate all the help. Thanks

Johnnie
Jan 18 '07 #9
ronverdonk
4,258 Recognized Expert Specialist
Well, I just did that part in your code again. Only I write the new file with the fputcsv php command. And it works as it should (I think). Look at the following snippet.
Expand|Select|Wrap|Line Numbers
  1. input file:
  2. ======
  3. aa1,bb1,cc1,dd1,ee1,ff1,gg1,hh1,ii1,jj1,kk1,ll1,mm1,nn1
  4. aa2,bb2,cc2,dd2,ee2,ff2,gg2,hh2,ii2,jj2,kk2,ll2,mm2,nn2
  5. aa3,bb3,cc3,dd3,ee3,ff3,gg3,hh3,ii3,jj3,kk3,ll3,mm3,nn3
  6.  
  7. output file:
  8. =======
  9. aa1,bb1,cc1,kk1,ll1mm1,nn1,English
  10. aa2,bb2,cc2,kk2,ll2mm2,nn2,English
  11. aa3,bb3,cc3,kk3,ll3mm3,nn3,English
  12.  
  13. Screen output:
  14. ==========
  15. Opened myinfile.txt for reading
  16. Opened myoutfile.txt for writing
  17. finished the import with a total of 3 records
PHP program:
[php]<?php
$inputfile = "myinfile.t xt";
$outputfile = "myoutfile.txt" ;
if (!$inputfp = fopen($inputfil e, "r"))
die("<br>Failed to open $inputfile");
else
echo "<br>Opened $inputfile for reading";
if (!$outfilefp = fopen($outputfi le, "w"))
die("<br>Failed to open $outputfile");
else
echo "<br>Opened $outputfile for writing";
//add English language codes to the end of each line
//Keep needed lines and push unwanted out
while ($row = fgetcsv($inputf p, 1000, ",")){
$phone = $row[11].$row[12];
$temp = array($row[0],$row[1],$row[2],$row[10],$phone,$row[13],$row[] = "English");
fputcsv($outfil efp, $temp);
$count++;
}
if ($count !== '0')
echo "<br>finish ed the import with a total of $count records";
else
echo "<br>Failed to import data";
?>[/php]
Ronald :cool:
Jan 18 '07 #10

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

Similar topics

2
2345
by: Steve Walker | last post by:
Hi all. I've been tasked with "speeding up" a mid-sized production system. It is riddled with nulls... "IsNull" all over the procs, etc. Is it worth it to get rid of the nulls and not allow them in the columns anymore? If so, how to go about removing the nulls with a script?
12
55532
by: Sam Collett | last post by:
How do I remove an item with a specified value from an array? i.e. array values 1,2,2,5,7,12,15,21 remove 2 from array would return 1,5,7,12,15,21 (12 and 21 are NOT removed, duplicates are also removed) So far I have (val is value, ar is array, returns new array):
10
12711
by: VA | last post by:
I got the following function to swap table columns from somewhere on the Internet function swapColumns (table, colIndex1, colIndex2) { if (table && table.rows && table.insertBefore && colIndex1 != colIndex2) { for (var i = 0; i < table.rows.length; i++) { var row = table.rows; var cell1 = row.cells; var cell2 = row.cells;
7
1432
by: Paul | last post by:
Hi I have a dropdown listbox that is populated by binding to a dataset. Anyhow just wondering if anyone knows how to remove one of the items in the dropdown list in code after the dataset has populated it? thanks. -- Paul G Software engineer.
9
6093
by: Steve | last post by:
How I can remove an AutoGenerated column? I wnat to inlcude the primary key in the resultset for creating some custom LinkButtons, but I don't want it (the PK) displayed in the DataGrid. I tried searching the columnheader text, but found that AutoGenerated columns are members of the Columns collection. From the msdn documentation: Note: ...
3
35196
by: Ronald S. Cook | last post by:
I have an ADO.NET DataTable with several columns. I would like to remove some columns. How can I do this. please?
7
6591
by: Susan Mackay | last post by:
I have a data table that is connected to a database table with a data adapter in the 'standard' manner. However I want to be able to remove selected rows from the data table (i.e. no longer include them in the set that is displayed to the user) but I don't want to delete the corresponding row from the database. I've tried using the...
0
5010
by: =?Utf-8?B?SlA=?= | last post by:
I have several data sources that use the same gridView. I need to remove columns from the gridview at run time where the DataBind.Eval statements dont apply to the query currently using the grid. I have discovered that using gridView.Columns.Remove(...) causes the gridView OnRowCommand to quit functioning for any columns that remain in the...
1
6847
by: Halfdood | last post by:
I am working on a data migration project using a pre-made SQL 2005 database. We need to migrate data to over 300 different talbes and the records number 20 million plus for some of the tables. We need to be able to insert values into multiple identity columns, so therefore SET IDENTITY_INSERT ON/OFF wont work. We can't simply use the...
0
7401
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7807
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7419
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7756
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3450
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3442
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1879
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
703
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.