Jump to content

Parsing and writing in file - advanced


black187

Recommended Posts

Hello,

 

I need help.

 

I have a file test.txt, and this content in it:

 

[group 1]
immediate=yes
links=1,14,12,22
avaliable=no

[group 2]
immediate=no
links=1,4,14,22

 

Now, I also have a WEB app with database, where I can change both groups, and the only this missing is, that when a change is made in on group, that I write it to the file test.txt.

I know how to write to files, but here is the problem (2 examples):

 

[*]If I change on the WEB page below group 1 from immediate=yes to immediate=no -> how can I change this in the file (just for group 1).

[*]If I change on the WEB page below group 2 to avaliable=yes -> how can I add this line in the file below group 2

 

To summarize - I have problems detecting where the group 1 or group 2 starts and end - so I only change for each group.

 

Link to comment
https://forums.phpfreaks.com/topic/225422-parsing-and-writing-in-file-advanced/
Share on other sites

Not sure why you simply aren't using a database for the info, BUT...

 

Just an idea (un-proof-read, untested)

perhaps restructure your text file ie

end each line with a new line character

the lines would essentially be 'records'. you would delimit the 'fields' using the pipe |

group numbers would always be sequential from 1 to xxx with NO missing numbers; however, other than a group number a 'record' could have all the other 'fields' empty.

 

ie - group#|immediate|links|available

 

line 1 = 0||| /* leave this line EXACTLY how it is, as it is used to simplify finding groups */

line 2 = 1|yes|1,14,12,22|no

line 3 = 2|no|1,4,14,22|

line 4 = 3|||

line 5 = 4|yes|1,14,12|yes

etc etc

 

to make a change

$lines = file("test.txt'); /* read the file into an array */
$what_group = 3; /* set what group # you are editing */
$new_array = explode("|", $lines[$what_group]); /* create a new array of the line data */
$available = "yes"; /* define the change you are making */
$new_array[3] = $available; /* put the new value into the appropriate 'field' */
$lines[$what_group] = implode("|", $new_array); /* replace the record with the revised record */
$content = implode("\n", $lines); /* prepare the data for writing */
file_put_contents("test.txt", $content); /* write the revised content to the file */

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.