Jump to content

split content of textfile..


webinferno

Recommended Posts

Hi all!

 

I have a code that save content from a form into a text-file

 


<?php
IF(isset($_POST['button'])){
	$fp = fopen('test.txt', "a");
			$msg = $_POST['one'] . "|" . $_POST['two'] . "|" . $_POST['tree'] . "\n";

	fwrite($fp, $msg);

	print ("Oki.. content saved.");

						}
	else {


?>



    <TABLE border="0" cellpadding="3" cellspacing="3">
<tr><td>
    <form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
    first:<br />
    <input type="text" name="one" size="45"><br />
    second:<br />
    <input type="text" name="two" size="45"><br />
    third:<br />
   <input type="text" name="tree" size="45"><br /><br />
    <INPUT type="submit" name='button' value="GO!" >

    </form>
    
    </td></tr></table>

    <?php}?>
    

 

And to show the content i use this code:

 


<?php
$fp = fopen('test.txt', "a");
			$msg = $_POST['one'] . "|" . $_POST['two'] . "|" . $_POST['tree'] . "\n";



$msg = file("test.txt");

	foreach ($msg AS $tmp){
		$array = explode("|",$tmp);
	echo  $array[0] . "|" . $array[1] . "|" .$array[2];
}

	?>

 

But it display the content like this:

 

1 2 3

1 2 3

1 2 3

etc.. how can i make it to display 1 2 3 1 2 3 1 2 3, instead?

3 lines side-by-side and then a new row with 3 lines side-by-side

 

Hope i made myselfe clear about what i need help with, cause i'm not that good in english and as you see i'm neither that good in PHP :P

but i'm learning ;)

Link to comment
https://forums.phpfreaks.com/topic/105441-split-content-of-textfile/
Share on other sites

 

You need to remove line-feed from each line you read then add a line-feed every three lines. Something like this:

 

<?php
$msg = file("test.txt");
$i = 1;
foreach ($msg AS $tmp)
{
    $tmp = trim($tmp);
    echo $tmp;
    if ($i%3 == 0) echo "\n";
    $i++;
}
?>

 

Assume your "test.txt" has 2 lines like this:

1 2 3

4 5 6

When you read it with file(), you get array $msg with 2 string elements. The first elements will be "1 2 3\n" with newline attached at the end and when you print it, "1 2 3" will be in a separate line. You need to remove newline if you want "4 5 6" printed on the same line. That is what trim() does.

 

<?php

$msg = file("test.txt");

$i = 1;

foreach ($msg AS $tmp)

{

    $tmp = trim($tmp);          // this remove new-line character from the end of string $tmp

    echo $tmp;

    if ($i%3 == 0) echo "\n";  // if $i is dividable by3 (e.g., 3, 6, 9) print a new-line

    $i++;

}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.