【问题标题】:Removing/Adding characters from the end of a Text file using PHP使用 PHP 从文本文件末尾删除/添加字符
【发布时间】: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);

【问题讨论】:

    标签: php mysql text character


    【解决方案1】:

    改变这一行

    $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, ', ') . ']';
    

    这有帮助吗?

    【讨论】:

      【解决方案2】:
      $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);
      

      【讨论】:

      • 我已经编辑了包含此解决方案的第一篇文章,但它似乎不起作用(虽然可能是我很愚蠢:P)
      • 这似乎只是在向文件写入“]”
      猜你喜欢
      • 2014-01-18
      • 1970-01-01
      • 2012-01-27
      • 2011-09-09
      • 1970-01-01
      • 2021-10-04
      • 2023-04-08
      • 2017-06-18
      • 2013-03-20
      相关资源
      最近更新 更多