Jump to content

Modify a text file


christa

Recommended Posts

Hi

I have a txt file as this:

[section1]
parameter1:2345|parameter2:goal|parameter3:other

[section2]
parameter1:444|parameter2:val|parameter3:gold

 

Now, i have to edit only one section (section1 or section2 or sectionN...) and edit the values of parameters via form. Then, update the file with new values.

The values are (in the above example): 2345, goal, other....

 

How can I do? please, also post a few of code and example, because i'm a newbie of php.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/68352-modify-a-text-file/
Share on other sites

Open the file and read it line by line to place it in a new structure:

 

<pre>
<?php
$data = <<<DATA
[section1]
parameter1:2345|parameter2:goal|parameter3:other

[section2]
parameter1:444|parameter2:val|parameter3:gold
DATA;

	$lines = explode("\n", $data);
	$section = 'none';
	foreach ($lines as $line) {
		if (preg_match('/\[([^]]+)\]/', $line, $matches)) {
			$section = $matches[1];
		}
		if (strpos($line, 'parameter') !== FALSE) {
			$array[$section] = preg_split('/parameter\d+:|\|/', $line, -1, PREG_SPLIT_NO_EMPTY);
		}
	}
	print_r($array);

?>
</pre>

Link to comment
https://forums.phpfreaks.com/topic/68352-modify-a-text-file/#findComment-343877
Share on other sites

thanks. But i've edit your code in order to obtain this (view image):

 

 

I use this code:

<form>
<?php
$filename = "file.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));

$lines = explode("\n", $contents);
	$section = 'none';
	foreach ($lines as $line) {
		if (preg_match('/\[([^]]+)\]/', $line, $matches)) {
			$section = $matches[1];
		echo "<input type='text' name='$section' value=$section><br />";
		}
		if (strpos($line, 'parameter') !== FALSE) {
			$array[$section] = preg_split('/parameter\d+:|\|/', $line, -1, PREG_SPLIT_NO_EMPTY);
			echo "<input type='text' name='$line' value=$array><br />";	
		}

	}

	//print_r($array);

fclose($handle);
?>
</form>

 

[attachment deleted by admin]

Link to comment
https://forums.phpfreaks.com/topic/68352-modify-a-text-file/#findComment-343912
Share on other sites

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.