Parsing text file with PHP

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lka527
    New Member
    • Apr 2010
    • 15

    #1

    Parsing text file with PHP

    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?

    Code:
    <?php
       
    //Change location to be where you put the file
    
    $file = fopen("C:\wamp\www\Other.txt", "r") or exit("Unable to 
    
    open file!");
    
    //Output a line of the file until the end is reached
    
    while(!feof($file)){
    echo fgets($file). "<br />";
    [B]
    
    //This is where you will need to parse through the file looking for the colon
    //And put the part after the colon into a variable as well as on  the screen[/B]
    
    }
    fclose($file);
    			
    ?>
  • chathura86
    New Member
    • May 2007
    • 227

    #2
    you can use the php explode() function

    Code:
    <?php
    
    	$file = fopen("info.txt", "r") or exit("Unable to open file!");
    
    	while(!feof($file))
    	{
    		$line = fgets($file); // Read a line.
    
    		//escape if the line is empty
    		if (trim($line) == "")
    			continue;
    
    		//explode from the :
    		$fields = explode(":", $line, 2);
    	}
    
    	fclose($file);
    ?>
    Regards

    Comment

    • lka527
      New Member
      • Apr 2010
      • 15

      #3
      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 :)




      Code:
      <?php
       
          $file = fopen("C:\wamp\www\Other.txt", "r") or exit
      
      ("Unable to open file!");
       
      while(!feof($file))
      {
      
      	$line = fgets($file); // Read a line.
       
              //escape if the line is empty
              if (trim($line) == "")
                  continue;
       
              //explode from the :
              $fields = explode(":", $line, "2");
      	
      
      	echo fgets($file). "<br />";
      	
          }
       
          fclose($file);
      ?>
      Last edited by Atli; Apr 5 '10, 05:33 AM. Reason: Please use [code] tags!

      Comment

      • chathura86
        New Member
        • May 2007
        • 227

        #4
        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

        Comment

        • lka527
          New Member
          • Apr 2010
          • 15

          #5
          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.

          Comment

          • chathura86
            New Member
            • May 2007
            • 227

            #6
            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

            Comment

            • Atli
              Recognized Expert Expert
              • Nov 2006
              • 5062

              #7
              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:
              [code=php]<?php
              // Suppose this is one line of your file.
              $line = "Key: value";

              // To get each side of the colon into separate
              // variables, you typically do something like:
              list($key, $value) = explode(": ", $line);

              // After which you can use the variables
              // as you see fit.
              echo "The key: $key - The value: $value";
              ?>[/code]

              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.

              Comment

              • chathura86
                New Member
                • May 2007
                • 227

                #8
                Originally posted by Atli
                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:
                [code=php]<?php
                // Suppose this is one line of your file.
                $line = "Key: value";

                // To get each side of the colon into separate
                // variables, you typically do something like:
                list($key, $value) = explode(": ", $line);

                // After which you can use the variables
                // as you see fit.
                echo "The key: $key - The value: $value";
                ?>[/code]

                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.
                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,

                Comment

                • lka527
                  New Member
                  • Apr 2010
                  • 15

                  #9
                  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,
                  Code:
                  <?php
                   
                      $file = fopen("C:\wamp\www\Other.txt", "r") or exit
                   
                  ("Unable to open file!");
                   
                  while(!feof($file))
                  {
                   
                      $line = fgets($file); // Read a line.
                  
                   
                         //escape if the line is empty
                          if (trim($line) == "")
                              continue;
                   
                          //explode from the :
                          $fields = explode(":", $line, "2");
                  
                  	list($key,$value) = explode (": ",$line);
                  	echo "the key: $key - the value: $value";
                   
                      }
                   
                      fclose($file);
                  ?>
                  I don't think this is right ... but what I tried is this..
                  I hope this is the last question I asked..:-(
                  Last edited by Atli; Apr 5 '10, 06:23 AM. Reason: Added [code] tags.

                  Comment

                  • chathura86
                    New Member
                    • May 2007
                    • 227

                    #10
                    you dont have to use the both

                    Code:
                    //explode from the :
                    $fields = explode(":", $line, 2);
                    
                    list($key,$value) = explode (": ",$line);
                    both lines does the same

                    use
                    Code:
                    list($key,$value) = explode (": ",$line, 2);
                    echo "the key: $key - the value: $value";
                    or

                    Code:
                    $fields = explode(":", $line, 2);
                    echo "the key: $fields[0] - the value: $fields[1]";
                    regards

                    Comment

                    • lka527
                      New Member
                      • Apr 2010
                      • 15

                      #11
                      I asked another question below.. Please review this and answer for me :(
                      Thank you so much

                      Comment

                      • lka527
                        New Member
                        • Apr 2010
                        • 15

                        #12
                        Notice: Undefined offset: 1 in C:\wamp\www\tes t.php on line 18
                        the key: High-Resolution CT Scans - the value:
                        Notice: Undefined offset: 1 in C:\wamp\www\tes t.php on line 18
                        the key: Center for Quantitative Imaging - the value:
                        Notice: Undefined offset: 1 in C:\wamp\www\tes t.php on line 18
                        the key: Penn State University - the value: the key: Machine - the value: PSU_225kV_30cmT T_RmtRecon_30UG 6003 the key: Plan - the value: TIM_BONE_NEW the key: Study - the value: MCZ_35677_H_MID SHAFT_20100118-142011 the key: Scan Type - the value: AxialCT the key: Date - the value: 2010.01.18 14:00:39 the key: Rows to Collect - the value: 139 the key: Energy Settings - the value: 180 kV, 0.11 mA the key: SOD - the value: 134.999 mm the key: Views/Average - the value: 1440 / 4 the key: Scale/Offset - the value: 45 / 1500 the key: Field of View - the value: 41.47 mm
                        Notice: Undefined offset: 1 in C:\wamp\www\tes t.php on line 18
                        the key: x = y = 0.040498046875 mm - the value:
                        Notice: Undefined offset: 1 in C:\wamp\www\tes t.php on line 18
                        the key: z = 0.043 mm - the value: the key: Matrix Size - the value: 1024x1024 the key: Number of Slices - the value: 1 16bit Tiff Images the key: Corrective Options - the value: the key: Number of Sectors in Polar Array - the value: 60 the key: Image Noise Threshold - the value: 200 the key: Ring Component Threshold - the value: 6000 the key: High Pass Adaptive Filter Length - the value: 11 the key: Low Pass Filter Distance - the value: 10 the key: Low Pass Number of Bindings - the value: 10


                        Alright,
                        this is my last question hopefully..
                        This result is what I just got when I replaced the thing as you told me to replace in the last reply.

                        I don't know what I should do now...:-(
                        I actually had more data than I posted in the first one..

                        Comment

                        • chathura86
                          New Member
                          • May 2007
                          • 227

                          #13
                          $line holds the line

                          echo $line will print the line

                          Regards

                          Comment

                          • chathura86
                            New Member
                            • May 2007
                            • 227

                            #14
                            can you attach the file?

                            Comment

                            • lka527
                              New Member
                              • Apr 2010
                              • 15

                              #15


                              is the text file I am supposed to parse..



                              Code:
                              <?php
                               
                                  $file = fopen("C:\wamp\www\Other.txt", 
                              
                              "r") or exit
                               
                              ("Unable to open file!");
                               
                              while(!feof($file))
                              {
                               
                                  $line = fgets($file); // Read a line.
                              
                               
                                   //escape if the line is empty
                                      if (trim($line) == "")
                                          continue;
                               
                                  $fields = explode(":", $line, "2");
                              echo "<b>$fields[0]</b>".": $fields
                              
                              [1]"."<br/>";
                               
                              
                              
                                  }
                               
                                  fclose($file);
                              ?>
                              this is what I actually have now
                              Last edited by Atli; Apr 5 '10, 06:24 AM. Reason: Added [code] tags.

                              Comment

                              Working...