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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.