473,698 Members | 2,152 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Parsing text file with PHP

15 New Member
In the code, I have bold text where I have a question.
I am not sure how to parse the file into different fields (right below with bold: machine,plan,st udy,scantype, date)... and I have more different files in the same format of this below.

Others also have machine,plan, study, scan type, date as their information.
right side of colon (:) have to be parsed separately..

Machine: 225kV_30cmTT_Rm tRecon_30UG6003
Plan: TIM_BONE
Study: MCZ_35677_20100 118-142011
Scan Type: AxialCT
Date: 2010.01.18 14:00:39


But I have no idea how to do this, can anyone help me out with this?

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. //Change location to be where you put the file
  4.  
  5. $file = fopen("C:\wamp\www\Other.txt", "r") or exit("Unable to 
  6.  
  7. open file!");
  8.  
  9. //Output a line of the file until the end is reached
  10.  
  11. while(!feof($file)){
  12. echo fgets($file). "<br />";
  13.  
  14. //This is where you will need to parse through the file looking for the colon
  15. //And put the part after the colon into a variable as well as on  the screen
  16.  
  17. }
  18. fclose($file);
  19.  
  20. ?>
  21.  
Apr 5 '10 #1
18 8683
chathura86
227 New Member
you can use the php explode() function

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3.     $file = fopen("info.txt", "r") or exit("Unable to open file!");
  4.  
  5.     while(!feof($file))
  6.     {
  7.         $line = fgets($file); // Read a line.
  8.  
  9.         //escape if the line is empty
  10.         if (trim($line) == "")
  11.             continue;
  12.  
  13.         //explode from the :
  14.         $fields = explode(":", $line, 2);
  15.     }
  16.  
  17.     fclose($file);
  18. ?>
  19.  
Regards
Apr 5 '10 #2
lka527
15 New Member
After I added

echo fgets($file). "<br />";

at the end of the php code I only got partial result in the page.
I got this below
Plan: TIM_BONE_NEW
Scan Type: AxialCT
I don't know why I am getting only partial data and I don't understand '2' in the php code you have given.. I am not really good at php and I really appreciate your help :)




Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3.     $file = fopen("C:\wamp\www\Other.txt", "r") or exit
  4.  
  5. ("Unable to open file!");
  6.  
  7. while(!feof($file))
  8. {
  9.  
  10.     $line = fgets($file); // Read a line.
  11.  
  12.         //escape if the line is empty
  13.         if (trim($line) == "")
  14.             continue;
  15.  
  16.         //explode from the :
  17.         $fields = explode(":", $line, "2");
  18.  
  19.  
  20.     echo fgets($file). "<br />";
  21.  
  22.     }
  23.  
  24.     fclose($file);
  25. ?>
Apr 5 '10 #3
chathura86
227 New Member
it is not appropriate to use

echo fgets($file). "<br />";

because what it does it read a line form the file, so next time when you
call it, it will read the next line.

so since you are reading a line in the while loop and also reading a it inside the
loop it will miss some lines.

read the fgets() in php manual for more details

Regards
Apr 5 '10 #4
lka527
15 New Member
Sir....
I am sorry that i keep asking you..
but in order to print every value how can I write this?
This is desperate for me:(
I tried to do this in array too but so confusing me..
Please let me know how to fix this into the better way.
Apr 5 '10 #5
chathura86
227 New Member
for each iteration $fields array holds the two parts of that line

eg.

iteration 1

$fields[0] holds Machine and
$fields[1] holds 225kV_30cmTT_Rm tRecon_30UG6003

iteration 2

$fields[0] holds Plan and
$fields[1] holds TIM_BONE

...

so every time you have an array with two values

Regards
Apr 5 '10 #6
Atli
5,058 Recognized Expert Expert
Hey.

The fgets function fetches a single line from the file. Your first example showed how you can use it to fetch every line in the file in a loop; one after another.

What you need to do is; rather than echo the line, you should put it into a variable. Then you can use the explode function to split the line in the variable into two pieces; the one before the colon and the one after it.

After that you can do whatever you need to with each piece. This example shows how we typically split a line into pieces:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // Suppose this is one line of your file.
  3. $line = "Key: value";
  4.  
  5. // To get each side of the colon into separate
  6. // variables, you typically do something like:
  7. list($key, $value) = explode(": ", $line);
  8.  
  9. // After which you can use the variables
  10. // as you see fit.
  11. echo "The key: $key - The value: $value";
  12. ?>
Remember, your original code already fetches each line. All you need to do is store the line returned by the fgets() function and apply the above method to it.
Apr 5 '10 #7
chathura86
227 New Member
@Atli
nice explanation

remember to put explode(":", $line, 2); 2 as the limit
because some of the rows contains : in the value also (Eg. 14:00:39)

Regards,
Apr 5 '10 #8
lka527
15 New Member
Thank you so much for your effort..
I am almost there, I think!

"Remember, your original code already fetches each line. All you need to do is store the line returned by the fgets() function and apply the above method to it."

You said this in the last part of your answer..
how can I store the line returned by the fgets() function?...
.. I just have no idea...T_T

This is what I got so far,
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3.     $file = fopen("C:\wamp\www\Other.txt", "r") or exit
  4.  
  5. ("Unable to open file!");
  6.  
  7. while(!feof($file))
  8. {
  9.  
  10.     $line = fgets($file); // Read a line.
  11.  
  12.  
  13.        //escape if the line is empty
  14.         if (trim($line) == "")
  15.             continue;
  16.  
  17.         //explode from the :
  18.         $fields = explode(":", $line, "2");
  19.  
  20.     list($key,$value) = explode (": ",$line);
  21.     echo "the key: $key - the value: $value";
  22.  
  23.     }
  24.  
  25.     fclose($file);
  26. ?>
I don't think this is right ... but what I tried is this..
I hope this is the last question I asked..:-(
Apr 5 '10 #9
chathura86
227 New Member
you dont have to use the both

Expand|Select|Wrap|Line Numbers
  1. //explode from the :
  2. $fields = explode(":", $line, 2);
  3.  
  4. list($key,$value) = explode (": ",$line);
  5.  
both lines does the same

use
Expand|Select|Wrap|Line Numbers
  1. list($key,$value) = explode (": ",$line, 2);
  2. echo "the key: $key - the value: $value";
  3.  
or

Expand|Select|Wrap|Line Numbers
  1. $fields = explode(":", $line, 2);
  2. echo "the key: $fields[0] - the value: $fields[1]";
  3.  
regards
Apr 5 '10 #10

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

Similar topics

4
2652
by: ralphNOSPAM | last post by:
Is there a function or otherwise some way to pull out the target text within an XML tag? For example, in the XML tag below, I want to pull out 'CALIFORNIA'. <txtNameUSState>CALIFORNIA</txtNameUSState>
3
3498
by: Pir8 | last post by:
I have a complex xml file, which contains stories within a magazine. The structure of the xml file is as follows: <?xml version="1.0" encoding="ISO-8859-1" ?> <magazine> <story> <story_id>112233</story_id> <pub_name>Puleen's Publication</pub_name> <pub_code>PP</pub_code> <edition_date>20031201</edition_date>
26
6866
by: SL33PY | last post by:
Hi, I'm having a problem parsing strings (comming from a flat text input file) to doubles. the code: currentImportDetail.Result = CType(line.Substring(7, 8).Trim(" "), System.Double) What is in my Watch:
1
2293
by: Thomas Kowalski | last post by:
Hi, I have to parse a plain, ascii text file (on local HD). Since the file might be many millions lines long I want to improve the efficiency of my parsing process. The resulting data structure shall look like this the following: class A { ... int value; }
4
6831
by: Neil.Smith | last post by:
I can't seem to find any references to this, but here goes: In there anyway to parse an html/aspx file within an asp.net application to gather a collection of controls in the file. For instance what I'm trying to do is upload a html file onto the web server, convert it to aspx file and then parse it for input tags/controls, which in turn will become fields in a newly created database table. Clearly when the aspx file is called the...
3
4378
by: toton | last post by:
Hi, I have some ascii files, which are having some formatted text. I want to read some section only from the total file. For that what I am doing is indexing the sections (denoted by .START in the file) with the location. And for a particular section I parse only that section. The file is something like, .... DATAS
2
2100
by: hzgt9b | last post by:
I've written a simple javascript page that parses an XML file... (Actually I just modified the "Parsing an XML File" sample from http://www.w3schools.com/dom/dom_parser.asp) The page works great standalone... but when I try to make this work under frames I get "Error: Object required" when the following line executes: xmlDoc.getElementsByTagName("to"); The standalone file is named treeView.htm (attached). You should be
13
4508
by: Chris Carlen | last post by:
Hi: Having completed enough serial driver code for a TMS320F2812 microcontroller to talk to a terminal, I am now trying different approaches to command interpretation. I have a very simple command set consisting of several single letter commands which take no arguments. A few additional single letter commands take arguments:
1
2147
by: martinsson | last post by:
Hi all! I'm pretty mad about this... dont know what is going on. Im parsing XML file that looks like this: <something> __<item att="something">text<item> __<item att="something">text<item> __<item att="something">text <span class="some">inside text</span> text<item>
2
2586
by: python | last post by:
I'm parsing a text file for a proprietary product that has the following 2 directives: #include <somefile> #define <name<value> Defined constants are referenced via <#name#syntax. I'm looking for a single text stream that results from processing a file containing these directives. Even better would be an iterator(?) type
0
8608
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,...
1
8898
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8870
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...
0
7734
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6524
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
5860
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
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2332
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2006
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.