Skip to content
Advertisement

How to extract in a text file only the needed data and save it to csv using php

I was given a text file that contains more than a hundred of rows with 6 columns but the data that i need are on column 3 and 6 and save it to a csv file. The text file contains like this:

JavaScript

By the way the text file came from a biometrics thumb print machine that records the following data above. Any help would be appreciated. Thanks in advance.

EDIT:

I tried this code but when i try to extract the necessary data i am getting an offset error:

JavaScript

This is the code that i successfully extract the data that i need but i want to explode the last column to separate date from time:

JavaScript

Advertisement

Answer

Does the source data contain a heading? According to your sample post the file is comma delimited, is that right? If yes, then I would use PHP to read the sample file and create an array. Something like this:

JavaScript

Instead of an echo command you would need to write code to write the data into a file.

EDIT – New program:

Here is a new program to try. Since you agreed with me that there were 7 columns this version will work. However, PHP date and time usually have a space between the date and time and not a tab. If there is a space and not a tab then this version will have to be tweaked a little.

JavaScript

Enjoy!

2nd EDIT:

Ok, just replace this line of code:

JavaScript

with these 2 lines of code:

JavaScript

EDIT – Final version

Ok, based on the fact that there is 1 tab between each column except for 3 tabs between 01408156 and 33 this works for me.

JavaScript

Let me know how it goes.

Last EDIT

I added headers to my sample and found I made a mistake. This line of code:

JavaScript

needs to be changed to this:

JavaScript

Unless, you want the 3 headers in your output file

New Final Version

Here is a version that doesn’t use array to build the output data. This version will read the input and write the output all at once.

JavaScript

Let me know how it works.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement