【发布时间】:2012-04-19 16:27:57
【问题描述】:
我有一个读取文本文件内容的自动填充搜索(此文本文件必须以正确的方式格式化,否则搜索不起作用)。现在我以一种相当冗长的方式来做这件事,因为我需要在文件的开头和结尾加上方括号。
从数据库中获取数据的php脚本:
$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);
}
第二个 php 脚本打开 data_old.txt 并以“[”开头,“]”结尾,然后将其保存为 data.txt:
$string1 = '[' . file_get_contents('data_old.txt') . ']';
$fp = fopen('data.txt', 'a');
fwrite($fp, $string1);
fclose($fp);
这会将数据保存为以下格式: (文件开头)
[{"key": "vodka", "value": "vodka"}, {"key": "tequila", "value": "tequila"}, {
(文件结束)
{"key": "brandy", "value": "brandy"}, {"key": "beer", "value": "beer"}, ]
我的问题是文件末尾有一个逗号和空格:}, ],我需要它看起来像这样:}]
我一直在谷歌搜索并尝试this 无济于事
(我需要代码来截断data.txt文件的最后2个字符并重新写入)
感谢任何帮助
-马特
edit2::
脚本1:
$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');
脚本2:
$string1 = '['. file_get_contents('data.txt') .']';
$fp = fopen('data.txt', 'a');
fwrite($fp, $string1);
fclose($fp);
【问题讨论】: