Deleting / Adding characters from the end of a text file using PHP

advertisements

I have an autofill search that reads the contents of a text file (this text file has to be formatted in the correct way or the search doesn't work). Now Im doing it in a rather long winded way because I need square brackets at the start and end of the file.

Php script that gets the data from database:

$getData = mysql_query("SELECT Name FROM tblIngredient"); 

 while($info = mysql_fetch_array($getData))
 {
    $string = '{"key": "'.$info['Name'].'", "value": "'.$info['Name'].'"}, ';
    $fp = fopen('data_old.txt', 'a');
    fwrite($fp, $string);
    fclose($fp);
 }

second php script that opens data_old.txt and writes it with "[" at the start and "]" at the end, then saves it as data.txt:

$string1 = '[' . file_get_contents('data_old.txt') . ']';
$fp = fopen('data.txt', 'a');
fwrite($fp, $string1);
fclose($fp);

This saves the data into this format: (start of file)

[{"key": "vodka", "value": "vodka"}, {"key": "tequila", "value": "tequila"}, {

(end of file)

{"key": "brandy", "value": "brandy"}, {"key": "beer", "value": "beer"}, ]

My problem is that at the end of the file there is a comma and space : }, ] and I need it to look like this: }]

I have been googling and tried this to no avail

(I need code to truncate the last 2 characters of the data.txt file and write it again)

Any help is appreciated

-Matt

edit2::

Script1:

$getData = mysql_query("SELECT Name FROM tblIndredient"); 

 while($info = mysql_fetch_array($getData))
 {
    $string = ', {"key": "'.$info['Name'].'", "value": "'.$info['Name'].'"}';
    $fp = fopen('data.txt', 'a');
    fwrite($fp, $string);
    fclose($fp);
 }

    $content = file_get_contents('data.txt');
    $content = '[' . ltrim('[, ', $content);
    file_put_contents('data.txt');

Script2:

    $string1 = '['. file_get_contents('data.txt') .']';
    $fp = fopen('data.txt', 'a');
    fwrite($fp, $string1);
    fclose($fp);


change this line

$string = '{"key": "'.$info['Name'].'", "value": "'.$info['Name'].'"}, ';

to

$string = ', {"key": "'.$info['Name'].'", "value": "'.$info['Name'].'"}';

and change this

$string1 = '['. file_get_contents('data.txt') .']';

to

$string1 = file_get_contents('data.txt');
$string1 = '[' . ltrim($string1, ', ') . ']';

does that help ?