[英]Removing/Adding characters from the end of a Text file using PHP
我有一個自動填充搜索,可以讀取文本文件的內容(此文本文件必須以正確的方式設置格式,否則搜索將不起作用)。 現在,我以一種相當漫長的方式進行操作,因為我需要在文件的開頭和結尾加上方括號。
從數據庫獲取數據的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"}, ]
我的問題是文件的末尾有一個逗號和空格:},],我需要它看起來像這樣:}]
我一直在谷歌搜索,並嘗試這樣做無濟於事
(我需要代碼來截斷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);
$string1 = '[' . file_get_contents('data_old.txt');
$fp = fopen('data.txt', 'a');
fwrite($fp, $string1);
fclose($fp);
$files = fopen('data.txt', 'w+');
$content = fread($files, filesize('data.txt'));
$content = substr_replace($content ,"", -2);
$content .= ']';
fwrite($files, $content);
fclose($files);
改變這條線
$ string ='{“ key”:“'。$ info ['Name']。'”,“ value”:“'。$ info ['Name']。'”},';
至
$ string =',{“ key”:“'。$ info ['Name']。'”,“ value”:“'。$ info ['Name']。'”}';;
並改變這個
$ string1 ='['。 file_get_contents('data.txt')。']';
至
$string1 = file_get_contents('data.txt');
$string1 = '[' . ltrim($string1, ', ') . ']';
這有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.