If I have a text file and in PHP for example want to read that test file but only a certain part what commands could I use to do this ? Sorry but I am a beginner in PHP and I am lost ...

Say for ex I have a txt file and the contents are one line ...

live life today (2:30)

and all I want to subract into a PHP variable say $time is the 2:30 in the ( ) is there programming code that allows me to do that ? or even if I wanted variable $word to say be the second word LIFE no matter how long the first word is ? in other words even if the txt file line was

second life today
or
then life sucks
or
live life well

etc etc is there a way to do this in PHP ?

I know how to do so in SHELL ( linux ) but not in php ?

Thanks;
Midnite

Recommended Answers

All 18 Replies

PHP is everything.... I mean you can do anything with PHP...

But I can't understand your question. Please Clarify that what actually you want to do...

I have a text file that constantly changes and at the end of the file is a number in a set of ( ) that also always changes what I want to do with PHP is open that text file read the one line and pull out only the information between the ( and the )

live life today (2:30)
take me home (1:45)
time will tell (3:15)

in other words in the above samples I want to assign a variable that will read the text file and grab the value inside the ( ) only ... like 2:30,1:45,3:15

there is only one line in the text file I just created 3 seperate examples above to better explain what I mean ...

can I tell php to read that line of text and only assign $time ( or any other variable ) to the time that is in the ( )

Thanks
Chad

by using this code I am printing the time only...
check it out...

<?php
  $fp=fopen("test.txt","r");
  while (!feof($fp))
{
$fstring = fread($fp,50);
$line_array = explode("(", $fstring);
}
		$time=$line_array[1];
		for($i=0;$time[$i]!=NULL;$i++)
	{
		if($time[$i]!=")")
		echo $time[$i];
	}

echo "\n";
?>

okey finally u just use this code, this is everything you want....

<?php
//openning file..
$fp=fopen("test.txt","r");

while (!feof($fp))
{
	$fstring = fread($fp,50); //Getting file as a string
	$line_array = explode("(", $fstring);	//using this condition to explode the string in two arrays, line_array[0] and line_array[1]
}
$time=$line_array[1];	//now line_array[1] have 3:15) so we are storing it to time array
$y=0;
for($i=0;$time[$i]!=NULL;$i++)
{
	if($time[$i]!=")")	//using this loop to remove ) from time array
	{
		//storing the time to a variable named maintime
		$maintime[$y]=$time[$i];
		$y++;
	}
}
echo "Wow... now i have stored time to an array..<br><b>The Time is : </b>";

//printing the variable in which i have stored the time only...
for($i=0;$maintime[$i]!=NULL;$i++)
echo $maintime[$i];

//clossing file
fclose($fp);
?>

have a great day... and yeah please let me know if you are solved. And you can ask more if you are not solved...

Bye....

That is EXACTLY what I am looking for ... could you have the same script do one more thing ? instead of grabbing all of the time in the ( ) can you have it grab the minute after the ( and before the : and then multiply that by 60 ( so it converts it to seconds and then grab the seconds after the : and before the ) and add it to the total after the minutes are being multiplied by 60

In other words if I posted

time for life (2:35) I would need the script to take the 2 and multiply it by 60 making that total 120 and then adding the 35 to it making th total time in seconds become 155

Please append that addition to your already amazing php script and upload it for me to learn from and use ... TY so very much in advance !!!

in other words the time is in a min and seconds fromat hence

(2min:35seconds) posted in my test file as (2:35) I need the script to do as I mentioned above and grab the minutes from the file first ... hence the 2 and times it by 60 to convert it to seconds ... then it needs to grab the 35 seconds and add that to the total getting 155 seconds in total ... I need that in a variable if possible and again TY so much

Chad

well I have done half work... please check it out... i have totaled the minutes but not added seconds of original source... so please try from your side. Right now I have some other work to do so i can't reply you much for today, but i will try to rich at you after a day... will definitely meet you tomorrow...

<?php
//openning file..
$fp=fopen("test.txt","r");

while (!feof($fp))
{
	$fstring = fread($fp,50); //Getting file as a string
	$line_array = explode("(", $fstring);	//using this condition to explode the string in two arrays, line_array[0] and line_array[1]
}
$time=$line_array[1];	//now line_array[1] have 3:15) so we are storing it to time array
$y=0;
for($i=0;$time[$i]!=NULL;$i++)
{
	if($time[$i]!=")")	//using this loop to remove ) from time array
	{
		//storing the time to a variable named maintime
		$maintime[$y]=$time[$i];
		$y++;
	}
}
//clossing file
fclose($fp);
echo "Wow... now i have stored time to an array..<br><b>The Time is : </b>";

//printing the variable in which i have stored the time only...
for($i=0;$maintime[$i]!=NULL;$i++)
echo $maintime[$i];

echo "<br><br>";
$y=0;
for($i=0;$maintime[$i]!=":";$i++)
{
	$minute[$y]=$maintime[$i];
	$y++;
}

echo "Minute is : $minute[0]";
$totsec=$minute[0] * 60;
echo "<br>";
echo "Total Seconds In : $totsec";
?>

Bye.... and please try to do this job from your side, after all i am always here for you....

Harsh Bavaliya, why do you manually loop through the strings like that?
PHP comes with a number of String functions that can take care of all of that for you. (The str* , trim and explode functions, in particular, would be useful in this case.)

Anyhow, this is how I would write this script:

<?php
// Open file
$fp = fopen('test.txt','rb');

// Read all the data into an array
if($fp)
{
    $data = array();
    while (!feof($fp))
    {
        // Split each line on the ( char, into the text and time parts.
	    $parts = explode('(', fgets($fp));

        // If the line doesn't have both parts, move on to the next line.
        if(count($parts) != 2) {
            continue;
        }

        // Get the text, removing all spaces around it.
        $text = trim($parts[0]);

        // Get the time, removing all spaces and ) chars around it.
        $time = trim($parts[1], " \0\t\r\n)");

        // Calculate the seconds in the $time value
        list($minutes, $seconds) = explode(':', $time);
        $total_seconds = ($minutes * 60) + $seconds;

        // Add the text, time, and seconds to the $data array.
        $data[] = array(
            'text' => $text,
            'time' => $time,
            'seconds' => $total_seconds
        );
    }

    // Close file
    fclose($fp);

    // This makes plain-text output look better in the browser.
    header('content-type: text/plain; charset=utf8');

    // Print the results:
    foreach($data as $_index => $_line) {
        echo " #{$_index}\n";
        echo "  Name: {$_line['text']}\n";
        echo "  Time: {$_line['time']} ({$_line['seconds']} seconds)\n";
        echo "\n";
    }
}
else {
    echo "Error opening the file!";
}
?>

This would output; for example:

#0
  Name: live life today
  Time: 2:30 (150 seconds)

 #1
  Name: take me home
  Time: 1:45 (105 seconds)

 #2
  Name: time will tell
  Time: 3:15 (195 seconds)

Hope that helps.

Atli, I was trying to teach him/her as smoothly as possible, because he/she said that he/she is a beginner, nothing else...

Atli, I was trying to teach him/her as smoothly as possible, because he/she said that he/she is a beginner, nothing else...

I see.
I guess we just have different views on what is smooth. Using the string functions looks somewhat smoother to me, and I would think beginners would find it easier to understand.

I mean:

$new = substr($old, strpos('(', $old));
$new = '';
$i = 0;
while($old[$i] != '(' && $old[$i] != null) {
    $new .= $old[$i];
    $i++;
}

Basically the same code, but I would think the first one would be easier to read for a beginner.

... But that's just me :)

then what about this code...?

<?php
// Open file
$fp = fopen('test.txt','rb');

// Read all the data into an array
if($fp)
{
    $data = array();
    while (!feof($fp))
    {
        // Split each line on the ( char, into the text and time parts.
	    $parts = explode('(', fgets($fp));

		$time = trim($parts[1], " \0\t\r\n)");

		list($minutes, $seconds) = explode(':', $time);

		$total_seconds = ($minutes * 60) + $seconds;
	}
}

echo "Other String is : $parts[0]<br>";
echo "Total Seconds are : $total_seconds";
?>

Actually, he/she was asking questions one by one, just check it....

then what about this code...?
...
Actually, he/she was asking questions one by one, just check it....

OK, if you want it one by one I would rewrite it as:

<?php
$fp = fopen('test.txt','rb');
if($fp)
{
    // Get the parts for the first line.
    $parts = explode('(', fgets($fp));

    // Extract and caclulate the seconds
    $time = trim($parts[1], " \0\t\r\n)");
    list($minutes, $seconds) = explode(':', $time);
    $total_seconds = ($minutes * 60) + $seconds;

    // Print the results.
    echo "Other String is : $parts[0]<br>";
    echo "Total Seconds are : $total_seconds";

    // Close the file
    fclose($fp);
}
else {
    echo "Failed to open file.";
}
?>

It has a few advantages over the version you posted

  • If the file fails to open, you get an error message instead of a broken version of the normal output.
  • Your version looped through the entire file, extracting and processing every line, but only displaying the last one. This version just grabs the first line and uses that. (You can add additional logic to "seek" the line you need, if that is required.)
  • You failed to close the file resource. Even tho this doesn't really matter for minor code snippets like these, it will matter in larger applications. You should at least include it in examples you write for others.

And This !

<?php
 <?php
// Open file
$fp = fopen('test.txt','rb');

// Read all the data into an array
if($fp)
{
    $data = array();
    while (!feof($fp))
    {
        // Split each line on the  :, (, and )
	    $parts = split('[/(:/)]', fgets($fp));
    }
}
$total=($parts[1]*60)+$parts[2];

echo "Minutes Are : $parts[1]<br>";
echo "Seconds Are : $parts[2]<br>";
echo "So Total Seconds Are ($parts[1] Minutes X 60) + $parts[2] Seconds : $total<br><br>";
echo "And Other Strings Are : $parts[0]";
?>

This is also gooooooooooooooooooood.....

Am I right Atli ?

Sorry I Hurry I have done one mistake in previous code. Please remove anyone

<?php

from that....

Sorry Once Again !

and the

else {
    echo "Failed to open file.";
}
?>

code is on the coder, if he want to display a massage, then it's okey to use it...

But it can be possible that a coder want to do something else, so I am not adding this code....

Have a nice day....
:)

And This !

This is also gooooooooooooooooooood.....

Am I right Atli ?

The idea is good, but there are a few things in your code that would worry me.

  • You are still looping through the entire text file, just to extract the last line. That's just a waste of resources.
  • The split function, and the rest of the POSIX functions, are deprecated. If you plan on using regular expressions, you should be using the PCRE (preg) functions (See the example below).
  • Your message is outside the scope where you define the $parts variable, and even where its guaranteed that the file is read. You should never assume variables are going to bleed down, outside the scope it is defined it. You are almost asking for undefined index issues.
  • I know you said you left out the error message intentionally, but I would still consider that a grave error. Error messages are our #1 source of info if we need to debug a problem. Leaving them out will just hurt you in the long run, and you should always at least include them in examples you write for others.

I would re-write your code to look like this:

<?php
$fp = fopen('test.txt','rb');
if($fp)
{
    if ($parts = preg_split('/[(:)]/', fgets($fp)))
    {
        $total=($parts[1]*60)+$parts[2];
        
        echo "Minutes Are : $parts[1]<br>";
        echo "Seconds Are : $parts[2]<br>";
        echo "So Total Seconds Are ($parts[1] Minutes X 60) + $parts[2] Seconds : $total<br><br>";
        echo "And Other Strings Are : $parts[0]";
    }
    else {
        echo "Data is corrupt";
    }
}
else {
    echo "File failed to open";
}
?>

Anyhow, if I you want to extract a single line using regular expressions, I would recommend something more along the lines of this. The pattern is a lot more flexible here, because we are actually searching for a patter, rather than using a regular expression to split the string.

<?php
// Set headers and debug configuration directives.
ini_set('display_errors', true);
error_reporting(E_ALL);
header('content-type: text/plain;');

// Open file
$fp = fopen('test.txt','rb');
if($fp)
{
    // Define a regular expression to extract the data.
    $regexp = '/([^(]+)\((\d+):(\d+)\)/iu';

    // Extract a single line from the input stream and process it.
    if(preg_match($regexp, fgets($fp), $matches))
    {
        // Fetch the parts returned by the regular expression
        $text = (string)$matches[1];
        $minutes = (int)$matches[2];
        $seconds = (int)$matches[3];

        // Calculate the total number of seconds
        $total_seconds = ($minutes * 60) + $seconds;

        // Print the info
        echo "{$text}\n";
        echo " - Time: {$minutes} minutes, {$seconds} seconds\n";
        echo " - Total seconds: {$total_seconds}\n";
    }
    else {
        echo "Data is corrupt.";
    }
}
else {
    echo "File failed to open.";
}
?>

This only reads a single line. If you want to read the all, it is as simple as changing the if(...) on line #15 to while(...) and removing the else { ... } that starts on line #30.

yeah ! that i want to say dear !

the main difference between you code and mine is

if ($parts = preg_split('/[(:)]/', fgets($fp)))

nothing else...

and please note that the split function is being included in PHP 6.0. So we must have some practices to use that ! m i right?

and if and while are not actually meaning for for this code. Using for, while, and if is not a matter because the loop will run only for a single time! because of the condition.....

:)

and please note that the split function is being included in PHP 6.0. So we must have some practices to use that ! m i right?

Where do you get that from?
The manual entires for all the POSIX functions (including split) clearly state that they have been made deprecated in 5.3, and will be removed in 6.0.

Warning
This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

and if and while are not actually meaning for for this code. Using for, while, and if is not a matter because the loop will run only for a single time! because of the condition.....

No, that is not true. Your code does:

while (!feof($fp))
{
    // Split each line on the  :, (, and )
    $parts = split('[/(:/)]', fgets($fp));
}

This will start at the first line and loop through until the end of the file ( while (!feof($fp)) ), each iteration fetching a single line from the file-input stream ( fgets($fp) ).

You are basically doing:

while (the end of the file has not been reached) {
    split the next line and put it into the $parts variable.
}
print the $parts variable.

Each iteration (for each line in the file) the $parts variable is overwritten by the values of the current line, so once the loop is finished, only the data for the last line remains.

the main difference between you code and mine is

if ($parts = preg_split('/[(:)]/', fgets($fp)))

nothing else...

Actually, because of how my code is structured - versus how your code is structured - my code is more efficient, due to the fact that your code loops unnecessarily through all the lines of the file, and in case the datafile gets lost or corrupted, it fails more gracefully.

I don't mean to sound competitive, or anything. I'm just trying to help by pointing out how things can be improved :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.