dourao1877 2012-04-18 15:03
浏览 869
已采纳

将PHP生成的JSON保存到文本文件中

(This question is following on from my previous problem which has been fixed (Here)

I found a similar question to this (Here) but the solution wasn't quite what I was looking for.

I currently have a JQuery styled autocomplete search engine on my site, called (fcbkcomplete). The original operation of the script ran from a .txt file, looked up the manually-entered values and outputted them in the autocomplete results. However, I want the script to get the values from a MYSQL database instead of being manually entered into a .txt file as I eventually want the user to have the option of adding their own values.

I have therefore made the Javascript call a .php file instead of .txt with this script in it:

//connection details

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

 while($info = mysql_fetch_array($getData)) 
 {
     echo "{\"key: value:\";
     echo $info['Name'];
     echo "key: value:\"";
     echo $info['Name'];
     echo "}, ";
 }

This script works and outputs the data in the correct format:

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

So I need to know how I then convert this JSON output into data.txt (so as the database table grows, the .txt file is updated automatically when the script is run)

This is the final step in the search on my site so any help is much appreciated.

-Matt

  • 写回答

4条回答 默认 最新

  • dsfdfdfd6576578 2012-04-18 15:13
    关注

    I can't really tell which bit of data you want to save to this txt file but I'm going to assume it's this:

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

    If it isn't you can just substitute it for what you want.

    I think the function you are looking for is fopen() specifically using 'a' as the second argument.

    From the manual:

    'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

    Here's an example (a very brief one at that) of how to use it.

    $string = '{"key": "vodka","value": "vodka"}, {"key": "tequila","value": "tequila"}';
    $fp = fopen('somefile.txt', 'a');
    fwrite($fp, $string);
    fclose($fp);
    

    One thing to consider here (amongst others) is the file will need the proper permissions for write access.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献