473,708 Members | 2,377 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 10996
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
2360
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
55570
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
12749
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
1434
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
6104
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: When the AutoGenerateColumns property is set to true, the columns created by the DataGrid control are...
3
35204
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
6606
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 .Rows.Remove() method but an exception is thrown to say I don't have a 'delete' command in the data...
0
5016
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 grid. (MS Please look into this, obviously a bug). So Ive been looking at other ways to hide the...
1
6858
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 interface either as it means that a miss click or a moment of absent mindedness can cause a world of...
0
8697
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9289
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9158
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9001
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6615
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5939
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4454
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3151
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
3
2096
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.